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.

SqlData Fetching

Code

snippet
-- 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

FAQ

What objects does the SQL involve?
`orders`.