Most searches are for app views, or for emails typed in any case. Partial indexes cover only some rows. Expression indexes index a calculation, like lower of email.
Where device equals app means only app views go in the index, so it's smaller. A query with the same condition can use it. Run it. The index is used, for app views only.
query.sqlsql
CREATE INDEX app_views ON page_views (book_id) WHERE device = 'app';EXPLAIN (ANALYZE, COSTS OFF, BUFFERS OFF, TIMING OFF)SELECT count(*) FROM page_viewsWHERE device = 'app' AND book_id = 7;
Output
CREATE INDEX
QUERY PLAN
-----------------------------------------------------------------------------------
Aggregate (actual rows=1.00 loops=1)
-> Index Only Scan using app_views on page_views (actual rows=3905.00 loops=1)
Index Cond: (book_id = 7)
Heap Fetches: 0
Index Searches: 1
Planning Time: 0.430 ms
Execution Time: 0.242 ms
(7 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;
Customers type emails in any case. An index on lower of email matches queries that use lower of email. Run it. An index scan, even though we searched in capitals.
query.sqlsql
CREATE INDEX customers_email_lower ON customers (lower(email));SET enable_seqscan = off; -- tiny table: force the index for the demoEXPLAIN (COSTS OFF)SELECT first_name FROM customersWHERE lower(email) = lower('TARA.BROWN@EXAMPLE.COM');
Output
CREATE INDEX
SET
QUERY PLAN
---------------------------------------------------------------------
Bitmap Heap Scan on customers
Recheck Cond: (lower(email) = 'tara.brown@example.com'::text)
-> Bitmap Index Scan on customers_email_lower
Index Cond: (lower(email) = 'tara.brown@example.com'::text)
(4 rows)