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.
Code
-- 高水位(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-levelWHEREwill 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
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 does this file reference?
- The references are `deploys`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.