bool_and And bool_or Flag Rollups
Roll up boolean flags per group with bool_and and bool_or, which ignore NULL inputs and return NULL when no non-null input exists.
Code
-- 布尔聚合:bool_and 全真才真(AND),bool_or 一真即真(OR)
CREATE TABLE health_checks (
node text NOT NULL,
ok boolean,
checked_at timestamptz NOT NULL
);
INSERT INTO health_checks VALUES
('web-1', true, now()), ('web-1', true, now()),
('web-2', true, now()), ('web-2', false, now()),
('web-3', NULL, now());
SELECT
node,
bool_and(ok) AS all_green, -- NULL 输入被忽略;没有任何非 NULL 输入时为 NULL
bool_or(ok) AS ever_up
FROM health_checks
GROUP BY node
ORDER BY node;What the code does
Several statements share this file — SELECT / INSERT / CREATE, with health_checks among the objects involved.
The SQL constructs in play: a GROUP BY that collapses matching rows into one output row per group; an ORDER BY that fixes the output order; NOT NULL qualifiers on the required columns.
Applying it
The health_checks table is the working surface here.
Statements that matter
SELECT
node,
bool_and(ok) AS all_green, -- NULL 输入被忽略;没有任何非 NULL 输入时为 NULL
bool_or(ok) AS ever_up
FROM health_checks
GROUP BY node
ORDER BY node;
INSERT INTO health_checks VALUES
('web-1', true, now()), ('web-1', true, now()),
('web-2', true, now()), ('web-2', false, now()),
('web-3', NULL, now());
CREATE TABLE health_checks (
node text NOT NULL,
ok boolean,
checked_at timestamptz NOT NULL
);
Interactive Tools for This Topic
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.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.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.SQL FormatterReformat SQL by uppercasing reserved words and breaking lines before SELECT, FROM, WHERE, and other clauses.
FAQ
- Which tables appear in this script?
- The references are `health_checks`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.