Sub topic 2
Sort order and ORDER BY with a multicolumn index
This chapter assumes you know basic SQL (SELECT, WHERE, ORDER BY, CREATE TABLE), that you have created a single-column B-tree index, and that you can read simple EXPLAIN output. The examples use the orders and users tables from the tutorial's running schema:
CREATE TABLE orders (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
customer_id bigint NOT NULL,
status text NOT NULL,
total_cents integer NOT NULL,
created_at timestamptz NOT NULL DEFAULT now()
);
CREATE TABLE users (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
email text NOT NULL,
deleted_at timestamptz
);Sort order and ORDER BY
A B-tree stores its entries in sorted order. A multicolumn index sorts by the first column, then by the second column within each value of the first. You can declare each column ascending or descending.
CREATE INDEX orders_customer_created_idx
ON orders (customer_id, created_at DESC);
EXPLAIN
SELECT *
FROM orders
WHERE customer_id = 42
ORDER BY created_at DESC
LIMIT 20;Because the index already holds one customer's rows newest first, PostgreSQL can read the first 20 entries and stop. It does not need a separate sort step. The plan should show an Index Scan with no Sort node. Sort direction matters only for mixed orders. A fully reversed order, such as ORDER BY created_at ASC with this index, can also be read backward, so the planner handles it too.
Partial indexes
A partial index is an index built on only the rows that match a WHERE predicate. It is smaller than a full index and cheaper to maintain.
CREATE INDEX orders_pending_created_idx
ON orders (created_at)
WHERE status = 'pending';Writing queries the planner can match
The planner uses a partial index only when your query's conditions imply the index predicate. Writing WHERE status = 'pending' in the query satisfies that requirement. Filtering on a different status does not.
EXPLAIN
SELECT id, created_at
FROM orders
WHERE status = 'pending'
AND created_at < now() - interval '1 hour';Check the plan with EXPLAIN after you create the index. If the predicate is written in a form the planner cannot prove, such as a parameter whose value is unknown at planning time, the index may be skipped.
Enforcing uniqueness on a subset of rows
A unique partial index applies the uniqueness rule only to rows that match its predicate. Here, active users must have distinct emails, while soft-deleted users can keep their old addresses.
CREATE UNIQUE INDEX users_active_email_key
ON users (email)
WHERE deleted_at IS NULL;Expression indexes
An expression index stores the result of a computed value. A query must use the same expression for the planner to consider the index.
CREATE INDEX users_lower_email_idx ON users (lower(email));
EXPLAIN
SELECT id FROM users WHERE lower(email) = '[email protected]';> The expression must be immutable, meaning it always returns the same result for the same input. A cast from timestamptz to date depends on the session time zone, so PostgreSQL rejects it in an index. Fix the zone inside the expression instead: ((created_at AT TIME ZONE 'UTC')::date).
Exercise
You created orderscustomercreatedidx on (customerid, createdat DESC). Will a query that filters only on createdat and sorts by it use this index efficiently? Explain why.
Show answer
Usually no. The leading column customerid is not constrained, so the index cannot narrow the search to a range. Create an index that leads with createdat, or add a customer_id condition to the query.