One Index Serves Filter Sort And Limit
Equality column first and sort column second lets one composite index answer WHERE, ORDER BY, and LIMIT without a separate sort step.
Code
-- one composite index serves filter, sort, and limit in a single pass
-- (status, created_at): equality filter column first, sort column second
CREATE TABLE orders (
order_id int GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
status text NOT NULL,
created_at timestamptz NOT NULL
);
CREATE INDEX orders_status_created_idx ON orders (status, created_at DESC);
-- filter, sort and limit all come from the index: no separate sort step
SELECT order_id, created_at
FROM orders
WHERE status = 'pending'
ORDER BY created_at DESC
LIMIT 20;
-- counterexample: a range column ahead of the leading one or mixed directions leaves the index partially usable and the rest falls back to sorting
SELECT order_id, created_at
FROM orders
WHERE created_at > now() - interval '1 day'
ORDER BY created_at DESC, status
LIMIT 20;Inside the snippet
SELECT / CREATE statements share the script, touching orders.
Mechanically, the statements are built from: a WHERE clause that keeps only the rows a statement is meant to touch; an ORDER BY that fixes the output order; a row cap (LIMIT) bounding the result size; NOT NULL qualifiers on the required columns; a PRIMARY KEY that enforces row identity; a GENERATED ALWAYS/GENERATED BY clause that computes the column value.
Putting it to use
Run the statement against the orders table; the LIMIT keeps the probe cheap while you tune the predicates.
Core lines
SELECT order_id, created_at
FROM orders
WHERE created_at > now() - interval '1 day'
ORDER BY created_at DESC, status
LIMIT 20;
SELECT order_id, created_at
FROM orders
WHERE status = 'pending'
ORDER BY created_at DESC
LIMIT 20;
CREATE TABLE orders (
order_id int GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
status text NOT NULL,
created_at timestamptz NOT NULL
);
Interactive Tools for This Topic
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.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.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.Line SorterSort text lines ascending or descending with numeric-aware ordering, duplicate removal, empty-line filtering, and locale-aware comparison.
FAQ
- What objects does the SQL involve?
- `orders`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.