We index viewed at. Now a filter on the last day can use the index. And order by viewed at descending with a limit reads the newest rows straight from the index, with no sorting. Run it. Both plans use the index.
query.sqlsql
CREATE INDEX views_time_idx ON page_views (viewed_at);EXPLAIN (COSTS OFF)SELECT count(*) FROM page_viewsWHERE viewed_at >= '2025-12-13';EXPLAIN (COSTS OFF)SELECT * FROM page_views ORDER BY viewed_at DESC LIMIT 5;
Output
CREATE INDEX
QUERY PLAN
---------------------------------------------------------------------------------------
Aggregate
-> Index Only Scan using views_time_idx on page_views
Index Cond: (viewed_at >= '2025-12-13 00:00:00+00'::timestamp with time zone)
(3 rows)
QUERY PLAN
--------------------------------------------------------------
Limit
-> Index Scan Backward using views_time_idx on page_views
(2 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;
Equals, less than and greater than. Between and in. Order by, in either direction. And like with a fixed start, like a prefix. It doesn't help with like starting with a percent sign.