bool_or Taints Sessions In A Running Window
bool_or over a running window taints every later request in a session once a failure appears, and bool_and confirms the whole session stayed clean.
Code
-- 会话健康面板:一旦出现错误,同一会话此后的每一行都标记为"已污染"
CREATE TABLE requests (
id integer PRIMARY KEY,
session_id integer NOT NULL,
failed boolean NOT NULL
);
INSERT INTO requests VALUES
(1, 100, false),
(2, 100, false),
(3, 100, true),
(4, 100, false),
(5, 200, false),
(6, 200, false);
SELECT
id,
session_id,
failed,
-- 运行窗口:从会话开头到当前行为止有没有失败过
bool_or(failed) OVER (PARTITION BY session_id ORDER BY id
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS session_tainted,
-- 全分区聚合:整个会话是否零失败
bool_and(NOT failed) OVER (PARTITION BY session_id) AS session_clean
FROM requests
ORDER BY session_id, id;How it works
SELECT / INSERT / CREATE statements share the script, touching requests.
Mechanically, the statements are built from: a window function (OVER (…)) calculating values across rows while every row stays visible; an ORDER BY that fixes the output order; NOT NULL qualifiers on the required columns; a PRIMARY KEY that enforces row identity.
What to watch for
- Window functions evaluate after
WHERE/GROUP BY, so filtering on their output in the same-levelWHEREwill not work — use an outer query or a CTE.
Using it
Point it at the requests table.
Key statements worth quoting
SELECT
id,
session_id,
failed,
bool_or(failed) OVER (PARTITION BY session_id ORDER BY id
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS session_tainted,
bool_and(NOT failed) OVER (PARTITION BY session_id) AS session_clean
FROM requests
ORDER BY session_id, id;
INSERT INTO requests VALUES
(1, 100, false),
(2, 100, false),
(3, 100, true),
(4, 100, false),
(5, 200, false),
(6, 200, false);
CREATE TABLE requests (
id integer PRIMARY KEY,
session_id integer NOT NULL,
failed boolean NOT NULL
);
Interactive Tools for This Topic
SQL DDL to TypeScript ConverterConvert SQL CREATE TABLE DDL statements into strict TypeScript interfaces with nullable, array, enum, JSONB, and Date or ISO string column mappings.PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.HTTP Retry & Backoff CalculatorSimulate exponential backoff retry schedules with Full, Equal, Decorrelated, or No Jitter to inspect per-attempt wait times and cumulative latency.
FAQ
- What are the relations in play here?
- `requests`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.