Running MAX High Water Mark

Track a cumulative high-water mark with MAX() OVER ordered frames, handling the empty first-row frame whose MAX evaluates to NULL.

SqlData Fetching

Code

snippet
-- 高水位(high water mark):每行携带"截至当前"的历史最大请求量
CREATE TABLE deploys (
    id        bigserial PRIMARY KEY,
    pushed_at date NOT NULL,
    requests  int  NOT NULL
);
INSERT INTO deploys (pushed_at, requests) VALUES
    ('2026-11-01', 9000),
    ('2026-11-02', 7100),
    ('2026-11-03', 12000),
    ('2026-11-04', 9800),
    ('2026-11-05', 15000);

SELECT
    pushed_at,
    requests,
    -- running max:默认 RANGE 帧从分区开头累积到当前行
    MAX(requests) OVER (ORDER BY pushed_at) AS high_water_mark,
    -- 严格超过此前所有行才标 record;首行帧为空时 MAX 为 NULL,比较落 ELSE 天然跳过
    CASE
        WHEN requests > MAX(requests) OVER (
                 ORDER BY pushed_at
                 ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING)
        THEN 'record'
        ELSE ''
    END AS new_record
FROM deploys
ORDER BY pushed_at;

How the snippet works

What runs here is SELECT / INSERT / CREATE — deploys are the objects involved.

In terms of clauses, the statements use: MAX aggregation; a window function (OVER (…)) computing values across rows without collapsing them; an ORDER BY that fixes the output order; NOT NULL qualifiers on the required columns; a PRIMARY KEY that enforces row identity.

Points of care

  • Window functions evaluate after WHERE/GROUP BY, so filtering on their output in the same-level WHERE will not work — use an outer query or a CTE.

Using it

Run the statement against the deploys table.

Key statements

INSERT INTO deploys (pushed_at, requests) VALUES
    ('2026-11-01', 9000),
    ('2026-11-02', 7100),
    ('2026-11-03', 12000),
    ('2026-11-04', 9800),
    ('2026-11-05', 15000);
CREATE TABLE deploys (
    id        bigserial PRIMARY KEY,
    pushed_at date NOT NULL,
    requests  int  NOT NULL
);

Interactive Tools for This Topic

FAQ

Which tables does this file reference?
The references are `deploys`.