- PostgreSQL
- Indexing
- Performance
Six scans to one in a Postgres summary query
A dashboard summary hit the statement timeout because it filtered the same rows again and again.
Mohammad Kazim · · 1 min read

The summary in my lead tracking project returned totals and several breakdowns for one organisation over a date range. Each number came from its own subquery, and each subquery filtered the events table from scratch. That was fine with little data and hit the statement timeout as the range filled up.
Read the rows once
A materialised common table expression selects only the columns the summary needs. Every count and breakdown then reads that set. Postgres can inline a CTE, so the keyword materialized states the intent.
create index if not exists events_org_created_summary_idx
on public.events (organization_id, created_at)
include (event_type, contact_id, city, device_type);
with scoped as materialized (
select e.event_type, e.contact_id, e.city, e.device_type
from public.events e
where e.organization_id = p_organization_id
)Let the index carry the columns
The existing index found the right rows quickly, but each row still had to be fetched from the table for four more columns. Adding them with include allows an index-only scan. Postgres can only skip the table for pages marked all-visible, so vacuum keeps this working.
Related case studyMulti-tenant lead tracking platform
