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.

SqlData Integrity

Code

snippet
-- 布尔聚合: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

FAQ

Which tables appear in this script?
The references are `health_checks`.