Riverside logs every page view, three hundred thousand rows so far. Finding one customer's views means checking every row. An index is a sorted shortcut, like the index at the back of a book.
Without an index, Postgres reads the whole table, a sequential scan. With a B tree index, it walks a small sorted tree to the matching entries. Then it fetches just those rows.
Explain analyze runs the query and shows how it ran. First, no index, so it's a sequential scan. Then we create an index, and run the same query. Run it. Same result, but the index scan is many times faster.
query.sqlsql
EXPLAIN (ANALYZE, COSTS OFF, BUFFERS OFF, TIMING OFF)SELECT * FROM page_views WHERE customer_id = 42;CREATE INDEX ON page_views (customer_id);EXPLAIN (ANALYZE, COSTS OFF, BUFFERS OFF, TIMING OFF)SELECT * FROM page_views WHERE customer_id = 42;
Output
QUERY PLAN
-----------------------------------------------------
Seq Scan on page_views (actual rows=588.00 loops=1)
Filter: (customer_id = 42)
Rows Removed by Filter: 299412
Planning Time: 0.227 ms
Execution Time: 8.050 ms
(5 rows)
CREATE INDEX
QUERY PLAN
------------------------------------------------------------------------------------
Bitmap Heap Scan on page_views (actual rows=588.00 loops=1)
Recheck Cond: (customer_id = 42)
Heap Blocks: exact=507
-> Bitmap Index Scan on page_views_customer_id_idx (actual rows=588.00 loops=1)
Index Cond: (customer_id = 42)
Index Searches: 1
Planning Time: 0.166 ms
Execution Time: 0.644 ms
(8 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;