Full answer
Sample schema and data:
CREATE TABLE orders (id int, customer_id int, created_at date);
INSERT INTO orders SELECT g, g % 1000, date '2026-01-01' + (g % 300) FROM generate_series(1, 30000) g;
CREATE INDEX orders_cust_created ON orders (customer_id, created_at);
ANALYZE orders;EXPLAIN (COSTS OFF) SELECT id FROM orders WHERE customer_id = 7 AND created_at >= '2026-06-01';Result:
Bitmap Heap Scan on orders
Recheck Cond: ((customer_id = 7) AND (created_at >= '2026-06-01'::date))
-> Bitmap Index Scan on orders_cust_created
Index Cond: ((customer_id = 7) AND (created_at >= '2026-06-01'::date))EXPLAIN (COSTS OFF) SELECT id FROM orders WHERE created_at = '2026-06-01';Output:
Bitmap Heap Scan on orders
Recheck Cond: (created_at = '2026-06-01'::date)
-> Bitmap Index Scan on orders_cust_created
Index Cond: (created_at = '2026-06-01'::date)CREATE INDEX orders_created ON orders (created_at); ANALYZE orders; EXPLAIN (COSTS OFF) SELECT id FROM orders WHERE created_at = '2026-06-01';PostgreSQL returns:
Bitmap Heap Scan on orders
Recheck Cond: (created_at = '2026-06-01'::date)
-> Bitmap Index Scan on orders_created
Index Cond: (created_at = '2026-06-01'::date)With customer_id fixed, the composite index narrows to one customer and then a date range, giving an efficient index scan. Filtering on created_at alone still uses the composite index here, but the condition can only be checked by reading the index under every one of the 1,000 customers, because the dates are spread through it; it wins over a table scan only because the index is smaller than the table. A dedicated index on created_at lets the same query jump straight to the matching entries. PostgreSQL 18 adds skip scans that help some of these cases, but on version 17 column order decides usability.
CREATE TABLE orders (id int, customer_id int, created_at date);
INSERT INTO orders SELECT g, g % 1000, date '2026-01-01' + (g % 300) FROM generate_series(1, 30000) g;
CREATE INDEX orders_cust_created ON orders (customer_id, created_at);
ANALYZE orders;
EXPLAIN (COSTS OFF) SELECT id FROM orders WHERE customer_id = 7 AND created_at >= '2026-06-01';
EXPLAIN (COSTS OFF) SELECT id FROM orders WHERE created_at = '2026-06-01';
CREATE INDEX orders_created ON orders (created_at); ANALYZE orders; EXPLAIN (COSTS OFF) SELECT id FROM orders WHERE created_at = '2026-06-01';Run on PostgreSQL 17.12 (Debian 17.12-0+deb13u1) in a fresh schema, twice, with identical output.
Key points
- Composite B-trees sort by the first column first
- Leading-column filters use the index well
- Filters on later columns alone must read the whole index
- Equality columns first, range columns last
- Add a separate index for other access paths
Common mistakes
- Adding composite indexes in arbitrary column order
- Assuming any column of an index is usable alone
Follow-ups
- How would you order columns for WHERE a = ? ORDER BY b?
- When is a bitmap AND of two indexes chosen?
Tips
- Explain the sort order