AI Hints
Home›PostgreSQL Tutorial›EXPLAIN ANALYZE and Smarter Indexes
PostgreSQL · Lesson 53 of 120

Multicolumn Indexes

Order matters.

⏱ 2 min read▶ Video at 46:36🎓 Free
Watch this lesson in the PostgreSQL courseWatch on YouTube ↗Full PostgreSQL course

The app often asks for one customer's views, newest first. One index on customer and time can do both the filter and the sort. But column order matters.

  • Filter by customer
  • Sort by time
  • One index

Filter and sort with one index

The index is on customer ID, then viewed at. The query filters by customer and sorts by time, so it reads the index in order, with no extra sort. Run it. An index scan, and a limit, with no sort step.

query.sqlsql
CREATE INDEX views_cust_time ON page_views (customer_id, viewed_at);

EXPLAIN (ANALYZE, COSTS OFF, BUFFERS OFF, TIMING OFF)
SELECT * FROM page_views
WHERE customer_id = 42
ORDER BY viewed_at DESC
LIMIT 5;
Output
CREATE INDEX
                                        QUERY PLAN
----------------------------------------------------------------------------------------
--
 Limit (actual rows=5.00 loops=1)
   ->  Index Scan Backward using views_cust_time on page_views (actual rows=5.00
   loops=1)
         Index Cond: (customer_id = 42)
         Index Searches: 1
 Planning Time: 0.504 ms
 Execution Time: 0.105 ms
(6 rows)
Also uses _setup.sql
SELECT setseed(0.42);
CREATE TABLE page_views (
  view_id     bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  customer_id integer NOT NULL,
  book_id     integer NOT NULL,
  device      text NOT NULL,
  viewed_at   timestamptz NOT NULL,
  ms          integer NOT NULL);
INSERT INTO page_views (customer_id, book_id, device, viewed_at, ms)
SELECT 1 + (random() * 499)::int, 1 + (random() * 29)::int,
       (ARRAY['web','web','web','app','app'])[1 + (random() * 4)::int],
       timestamptz '2025-01-01' + (g * interval '100 seconds'),
       50 + (random() * 900)::int
FROM generate_series(1, 300000) g;
VACUUM ANALYZE page_views;
ALTER DATABASE riverside SET max_parallel_workers_per_gather = 0;

Column order

Put columns you filter with equals first. Then columns for ranges or sorting. An index on a and b helps queries on a, or a and b, but usually not b alone. And include adds extra columns for index only scans.

keyvalue
First= columns
Thenrange / sort
(a, b)helps a, a+b
INCLUDE (c)index-only scans

Summary

Multicolumn indexes serve filters and sorts together, with equals columns first. Next, partial and expression indexes.

Key takeaways
  • (a, b)
  • Order matters
  • No sort
Next up: Partial and Expression Indexes — smaller, smarter