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.
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_viewsWHERE customer_id = 42ORDER BY viewed_at DESCLIMIT 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)::intFROM generate_series(1, 300000) g;VACUUM ANALYZE page_views;ALTER DATABASE riverside SET max_parallel_workers_per_gather = 0;
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.