MIN MAX Queries Use Index Bounds

A plain min or max becomes an index-endpoint InitPlan in EXPLAIN, independent of table size; ORDER BY plus LIMIT 1 fetches the whole oldest row the same way.

SqlData Integrity

Code

snippet
-- min/max does not need a full table scan: the planner compiles it into an index-endpoint hop (InitPlan)
CREATE TEMP TABLE events (
    id         bigint GENERATED ALWAYS AS IDENTITY,
    created_at timestamptz NOT NULL,
    detail     text
);

CREATE INDEX idx_events_created_at ON events (created_at);

INSERT INTO events (created_at, detail)
SELECT now() - g * interval '1 minute', 'row ' || g
FROM generate_series(1, 500) g;

ANALYZE events;

-- one query mixing min and max: EXPLAIN shows a Result node carrying two InitPlans,
-- each InitPlan performs one index-endpoint lookup, with a cost independent of the table row count
EXPLAIN (COSTS OFF)
SELECT min(created_at), max(created_at) FROM events;

-- need the whole "oldest row": ORDER BY + LIMIT 1 reuses the same index, again a single hop
EXPLAIN (COSTS OFF)
SELECT * FROM events ORDER BY created_at LIMIT 1;

How the snippet works

The file runs SELECT / INSERT / CREATE / EXPLAIN statements, touching events and generate_series.

events is created in this same file as session-local temp tables — nothing needs to exist beforehand, and it goes away at session end.

Mechanically, the statements are built from: MIN, MAX aggregation; an ORDER BY that fixes the output order; a row cap (LIMIT) bounding the result size; NOT NULL qualifiers on the required columns; a GENERATED ALWAYS/GENERATED BY clause that computes the column value.

Applying it

Setup is internal: the session-local tables it queries (events) are made by the file, so a single complete run against a scratch database suffices.

Statements that matter

INSERT INTO events (created_at, detail)
SELECT now() - g * interval '1 minute', 'row ' || g
FROM generate_series(1, 500) g;
CREATE TEMP TABLE events (
    id         bigint GENERATED ALWAYS AS IDENTITY,
    created_at timestamptz NOT NULL,
    detail     text
);
EXPLAIN (COSTS OFF)
SELECT min(created_at), max(created_at) FROM events;

Interactive Tools for This Topic

FAQ

Which tables does the SQL touch?
`events`, `generate_series`.