Quick revision
The short answer
First I would read the plan to see whether the 40 seconds come from a fixable problem, such as a sort or hash aggregate spilling past work_mem, no parallel workers, joins done before aggregation, or too many columns read. The structural fix is to stop aggregating 300 million rows on every page load: pre-aggregate into a summary table or a materialized view refreshed concurrently, aggregate before joining dimensions, and partition by date so only recent data is recomputed. For heavier analytics a columnar store fed by CDC is the long-term answer, and I choose by how fresh the numbers must be, how much incremental maintenance costs, and who owns the pipeline.
What to remember
In this answer, we started with the plan to find spills, missing parallelism, joins before aggregation and wide reads, and applied quick fixes such as aggregating before joining. The structural fix is to pre-aggregate with a materialized view refreshed concurrently or an incrementally maintained summary table, helped by date partitioning, and to move heavy analytics to a columnar store fed by CDC. The choice depends on freshness, maintenance cost and ownership.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
First I would read the plan to see whether the 40 seconds come from a fixable problem, such as a sort or hash aggregate spilling past work_mem, no parallel workers, joins done before aggregation, or too many columns read. The structural fix is to stop aggregating 300 million rows on every page load: pre-aggregate into a summary table or a materialized view refreshed concurrently, aggregate before joining dimensions, and partition by date so only recent data is recomputed. For heavier analytics a columnar store fed by CDC is the long-term answer, and I choose by how fresh the numbers must be, how much incremental maintenance costs, and who owns the pipeline.
Why this question is asked
Dashboards tend to start as one honest query: group the order items by day and region and sum them. It works fine with a few million rows. Two years later the same query reads 300 million rows every time someone opens the page, takes 40 seconds, and competes with checkout for the database. Interviewers ask this scenario because the right answer is a sequence of decisions rather than a single trick, and because it shows whether we can match a technical fix to a business need such as freshness. In this answer, we will read the plan first, look at quick query fixes, then pre-aggregation, partitioning and a separate analytical store, and finally how to choose between them.
1Reading the Plan First
Before changing the design, I would run the dashboard query with EXPLAIN (ANALYZE, BUFFERS) on production-like data. It shows where the 40 seconds go. Typical findings are a HashAggregate or Sort that spills to disk because work_mem, the memory each sort or hash may use, is too small; a plan that uses no parallel workers; a join to products and regions done on all 300 million rows before grouping; or a scan reading wide rows when the query needs only four columns.
Each of these lines points to a different fix, so reading the plan avoids guessing. Some fixes take an hour; others change the architecture.
2Quick Fixes in the Query Itself
If the aggregate spills, raising work_mem for this query's session, for example SET LOCAL work_mem = '256MB' inside its transaction, can turn a disk-based aggregate into an in-memory one. If no parallel workers are launched, checking max_parallel_workers_per_gather and the table size often helps, since PostgreSQL can split the scan and the aggregate across workers. A covering index on (created_at, store_id, amount) can allow an index-only scan of just the needed columns.
The most useful rewrite is to aggregate first and join the dimension tables afterwards. Instead of joining 300 million items to stores and regions and then grouping, we group items by day and store, which yields perhaps 90 days times 2,000 stores, 180,000 rows, and then join those few rows to regions.
These fixes might bring 40 seconds down to 8. That helps, but it is still reading 300 million rows on every page load, so for a dashboard opened hundreds of times a day it is not enough.
3Pre-Aggregating: Summary Tables and Materialized Views
The real fix is to compute the aggregate once and read the result many times. The simplest form is a materialized view, a stored query result that we refresh on a schedule. With a unique index on it, PostgreSQL can refresh it CONCURRENTLY, which lets readers keep reading the old contents during the refresh.
| Option | Freshness | Cost | Owner |
|---|---|---|---|
| Tune the query (work_mem, parallel, aggregate first) | Live | Low, but still scans each load | Service team |
| Materialized view, refreshed concurrently | As often as the refresh | Full recompute each refresh | Service team |
| Incremental summary table | Minutes | Write path or job to maintain | Service team |
| Partitions plus summaries of closed days | Recent data live | Partition management | Service team |
| Columnar warehouse fed by CDC | Minutes, by pipeline | New infrastructure | Data platform |
The catch is that a refresh recomputes everything, all 300 million rows, every time. For a refresh every hour that may be acceptable; for numbers that must be five minutes fresh, it is not. Then a summary table maintained incrementally works better: a scheduled job recomputes only the last two days and upserts those rows, or a consumer of order events adds each new item to its day and region row as it arrives.
4Partitioning by Date
Partitioning the order_items table by month or by day means each partition holds only one period. Queries for the last 90 days touch only those partitions, which PostgreSQL finds by partition pruning. It also fits nicely with summaries: once a month is closed and late corrections have stopped, we summarise that partition once and never touch it again, and only the current partitions are aggregated live or incrementally. Old partitions can later be detached and archived cheaply.
5Moving Analytics to a Columnar Store
If the dashboard is the first of many, with slicing by product, channel and hour, the OLTP database is the wrong tool. Row-oriented storage reads whole rows to sum one column. A columnar store, such as a cloud warehouse, ClickHouse, or an analytical engine over Parquet files, reads only the needed columns, compresses them heavily, and is built for scanning billions of rows. We would feed it with change data capture from PostgreSQL through Debezium and Kafka, for example, so the OLTP database does no analytical work at all.
6How I Choose
I decide with three questions. How fresh must the numbers be? If yesterday's totals are enough, a nightly summary is simplest; if five minutes, incremental maintenance; if truly live, live queries over small recent partitions plus summaries of the past. What does maintenance cost? Updating a summary row on every order adds write load and contention on hot rows, such as today's row for a busy region, so batching updates every minute is often a better trade. Who owns the pipeline? A service team can own a materialized view; a warehouse with CDC needs a data platform team to run it, and creating that ownership is a bigger decision than the dashboard itself.
7Follow-up questions
How do you keep a summary table correct when late orders arrive?
We aggregate by the business date of the order, not the time it reached us, and we recompute a sliding window rather than only the current day. A job that rebuilds the last three days every 10 minutes and upserts those summary rows absorbs late arrivals within that window. For corrections older than the window, we either recompute the affected day when such a change is detected, using created_at of the changed rows from CDC, or run a nightly reconciliation that compares summary totals with the source for recent months and fixes any difference.
Why not just add a read replica for the dashboard?
A replica moves the load off the primary, which protects checkout, but the query still takes 40 seconds there. It is a useful first step while building pre-aggregation, not a solution on its own.
8Conclusion
In this answer, we started with the plan to find spills, missing parallelism, joins before aggregation and wide reads, and applied quick fixes such as aggregating before joining. The structural fix is to pre-aggregate with a materialized view refreshed concurrently or an incrementally maintained summary table, helped by date partitioning, and to move heavy analytics to a columnar store fed by CDC. The choice depends on freshness, maintenance cost and ownership.
Open with
I'd start with EXPLAIN ANALYZE with BUFFERS, because the plan tells me whether the 40 seconds come from a hash aggregate spilling past work_mem, no parallel workers, joins to dimension tables done on all 300 million rows, or reading columns we don't need.
Then, if they want more
Some quick fixes help: more work_mem for that query, parallelism, a covering index, and aggregating order items by day and store first and joining regions afterwards, which turns 300 million rows into a few hundred thousand before the join. But a dashboard shouldn't scan 300 million rows on every page load, so the real fix is pre-aggregation.
If hourly freshness is fine, a materialized view with a unique index refreshed CONCURRENTLY is simplest. If it needs minutes, I'd maintain a summary table incrementally, recomputing the last few days on a schedule so late orders are absorbed. Partitioning by date helps too: recent partitions stay live and closed months are summarized once.
If analytics keeps growing, I'd move it to a columnar store fed by CDC. I'd choose based on required freshness, the write cost of incremental maintenance, and who will own the pipeline.
About this answer
- Last updated
- 12 November 2026
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
- Official documentation
- PostgreSQL documentation, The SQL Language
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "A dashboard query aggregates 300 million order_items rows per day and region every time...": https://scrivio-interview-library.netlify.app/databases/sql-fundamentals/4954782544/