Skip to content
Tech Interview Prep
Technical interview guide

Aggregations & GROUP BY

Collapsing many rows into one summary row per group (counts, sums, and averages) plus the HAVING clause that filters groups.

Minutes to read
3
Practice MCQs
25
Interview Q&A
25
Edition
v4
Editorial status
Reviewed

Scope: SQL principles with PostgreSQL 18 examples; vendor-specific behavior must be verified.

Interview Q&A

Treat each question like a live interview question: answer out loud first (structure, assumptions, tradeoffs), then open the model answer to spot gaps and rehearse a tighter follow-up.

Curated: · Written: · Reviewed:

25 questions

Q&A-12

Explain COUNT(*), COUNT(column), and COUNT(DISTINCT column) with a case where choosing wrongly matters.

Answer

The 60-second answer. COUNT(*) counts rows. COUNT(col) counts rows where col IS NOT NULL. COUNT(DISTINCT col) counts distinct non-NULL values of col. They diverge in two places: outer joins, and joins that fan out.

The case that bites is "how many orders has each customer placed?":

SQL
SELECT c.id, COUNT(*) AS n_star, COUNT(o.id) AS n_col
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.id
GROUP BY c.id;

For a customer with no orders, the LEFT JOIN emits exactly one row with every o.* column NULL. COUNT(*) counts that row, so it returns 1. COUNT(o.id) skips it and returns 0. COUNT(*) therefore reports that every customer has at least one order: no error, no warning, just a plausible-looking report claiming all 2,000,000 customers ordered.

customerjoined rowsCOUNT(*)COUNT(o.id)
c1, 3 orders333
c2, 0 orders1 NULL-extended10

Fan-out. The distinct form matters when the join multiplies rows:

SQL
SELECT COUNT(c.id) AS wrong, COUNT(DISTINCT c.id) AS right
FROM customers c JOIN orders o ON o.customer_id = c.id
WHERE o.created_at >= '2024-06-01';

If 300,000 customers placed 1,200,000 orders in June, wrong is 1,200,000 and right is 300,000. The tell is a customer count larger than the customer table: obvious if you know the magnitude, invisible otherwise.

Why COUNT(DISTINCT) costs. COUNT(*) and COUNT(col) use an incremental transition: one counter per group. COUNT(DISTINCT col) has to remember every value it has seen, so it becomes a sort or hash aggregate over the group's values. In PostgreSQL 13+ a hash aggregate that outgrows work_mem (default 4 MB) spills to disk; before 13 it simply used more memory than work_mem. Arithmetic: COUNT(DISTINCT order_id) over 50M rows holds ~50M entries; at roughly 32 bytes per hash-table entry that is ~1.6 GB against a 4 MB default. That is a spill, not a counter. (Estimate, not a benchmark.)

Approximations. BigQuery, Snowflake and Spark SQL all ship APPROX_COUNT_DISTINCT (HyperLogLog); Snowflake documents a maximum relative error of 1.6%. PostgreSQL has no built-in equivalent: you need an extension. Reach for it when the number is a dashboard figure, not when it is a billing total. Otherwise pre-aggregate so the distinct count runs over fewer rows, or maintain a summary table.

Free probe. On a base table, COUNT(*) - COUNT(col) is exactly the NULL count of col.

Engine notes. MyISAM keeps an exact row count, so COUNT(*) is O(1); InnoDB does not and scans the smallest index. PostgreSQL has no stored count either: COUNT(*) can use an index-only scan on the smallest index, but COUNT(col) needs col in that index.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-1

Explain the difference between WHERE and HAVING, including when the results differ.

Answer

The 60-second answer. WHERE filters rows on the way into grouping; HAVING filters groups on the way out. The logical pipeline is FROM → WHERE → GROUP BY → HAVING → SELECT → ORDER BY, so when WHERE runs there are no groups and no aggregate values yet, which is why WHERE COUNT(*) > 5 is a syntax error and HAVING COUNT(*) > 5 is not. HAVING can reference grouping columns and aggregates; WHERE can reference only input columns.

Where they genuinely differ. Take this table:

idcustomerstatusamount
1–6alicepaid100.00 … 600.00
7–8bobpaid10.00, 20.00
9–14bobcancelled30.00 … 80.00
15–17carolpaid5.00, 7.00, 9.00
18–21carolcancelled1000.00 … 4000.00

Two queries that both read as "customers with more than five orders":

SQL
-- A
SELECT customer, COUNT(*) AS paid_orders
FROM orders
WHERE status = 'paid'
GROUP BY customer
HAVING COUNT(*) > 5;

WHERE keeps 11 rows (alice's 6, bob's 2, carol's 3). Groups: alice 6, bob 2, carol 3. HAVING keeps alice only.

 alice | 6
SQL
-- B
SELECT customer, COUNT(*) FILTER (WHERE status = 'paid') AS paid_orders
FROM orders
GROUP BY customer
HAVING COUNT(*) > 5;

All 21 rows are grouped: alice 6, bob 8, carol 7. HAVING keeps all three; paid_orders counts only paid rows inside each group.

 alice | 6
 bob   | 2
 carol | 3

Different answer sets, and the reason is the one that matters: in A the predicate decides which rows exist for the whole query; in B it decides only what one measure counts while the group keeps every row. Bob has eight orders and two paid ones: A never sees him, B reports him with 2.

When they're interchangeable. A predicate on a grouping column is legal in both places and means the same thing: HAVING region = 'EU' and WHERE region = 'EU' produce identical results. Put it in WHERE anyway: it cuts rows before the grouping step rather than after, and the optimiser is not obliged to push it down for you. On a 100M-row table with a 1% selective predicate that is grouping 1M rows instead of 100M. HAVING with no GROUP BY treats the whole result as a single group, which is occasionally what you want and usually a bug.

Failure modes.

  • Non-grouping predicate in HAVING. HAVING status = 'paid' is rejected by PostgreSQL and by standard SQL. MySQL accepts it when ONLY_FULL_GROUP_BY is off and evaluates it against an arbitrary row in the group: silently wrong, not an error. Detect it by turning ONLY_FULL_GROUP_BY on (default since MySQL 5.7.5) or running the query on PostgreSQL.
  • NULLs. WHERE status = 'paid' drops NULL-status rows before grouping, so a customer whose only rows are NULL disappears entirely; the same predicate in HAVING would have kept the group and failed the test. And COUNT(col) skips NULLs while COUNT(*) does not, so a HAVING on COUNT(col) can drop groups you expected to keep.
  • Alias in HAVING. MySQL resolves the SELECT alias there; PostgreSQL does not. HAVING paid_orders > 5 works on one and errors on the other.
  • FILTER availability. FILTER (WHERE ...) is standard and supported by PostgreSQL (9.4+), SQLite (3.30+) and DuckDB; MySQL, MariaDB, SQL Server and Oracle do not have it. The portable equivalent is COUNT(CASE WHEN status = 'paid' THEN 1 END).

The rule. Put a predicate in WHERE when it defines which rows are in scope for the whole question. Use FILTER (or a CASE inside the aggregate) when it defines which rows one measure counts while the other aggregates still see everything. If the predicate is on a grouping column, WHERE.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-2

How do NULLs affect aggregate results, and where does that cause bugs?

Answer

Aggregates skip NULL inputs. AVG over ten rows with three NULL scores divides by seven. That is usually the intended meaning, a missing score is not a zero, but it must be a decision rather than an accident, because AVG(COALESCE(score, 0)) gives a different and equally defensible answer depending on what the metric means.

COUNT is where the distinction is clearest. COUNT(*) counts rows; COUNT(col) counts non-NULL values; COUNT(DISTINCT col) counts unique non-NULL values. The gap between the first two is exactly the NULL count, which makes it a useful one-line data-quality probe.

The bug that bites hardest is SUM over an empty set returning NULL rather than 0. COUNT returns 0 in that case, so people generalise incorrectly. A dashboard tile then shows blank instead of zero, or downstream code dereferences a null. COALESCE(SUM(x), 0) is the fix, and I apply it by default in reporting queries.

GROUP BY behaves opposite to comparison: all NULLs in a grouping column collapse into one group, because grouping uses not-distinct-from rather than equality. So a report grouped by a nullable category silently gets an unlabelled bucket, which people misread as a category named nothing rather than as missing data. I usually surface it explicitly with COALESCE(category, 'Unknown') so the reader knows what they are seeing.

The last one is outer joins manufacturing NULLs. After a LEFT JOIN, COUNT(child.id) counts only real matches while COUNT(*) counts the NULL-extended rows too, so a 'number of orders per customer' query returns 1 rather than 0 for customers with no orders unless you count the child key rather than the rows.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-14

Explain how aggregation is executed, and what that implies for tuning.

Answer

There are two main strategies and knowing which one you got explains most tuning decisions.

A hash aggregate builds a hash table keyed by the grouping expressions, updating each group's running state as rows stream past. It needs no sorted input, so it is usually chosen, and its memory is proportional to the number of groups, not rows. Aggregating a billion rows into ten groups is cheap; aggregating a million rows into 900,000 groups is not. When the hash table exceeds working memory the engine spills to disk, and that is the cliff behind most 'fast in staging, slow in production' aggregation reports.

A group aggregate requires input sorted by the grouping key and then collapses adjacent runs. Its memory is constant regardless of group count, so the planner prefers it when cardinality is high, or it may be nearly free when an index already provides the ordering, since no sort is needed at all.

The tuning levers follow directly. Reduce rows before aggregating, which is why non-aggregate predicates belong in WHERE. Reduce group count by grouping on fewer or coarser columns. Provide an index matching the grouping and ordering columns so the sorted path is available without a sort. Narrow the projection so an index-only scan is possible. Raise working memory for a specific important query rather than globally, if a spill is the confirmed cause.

COUNT(DISTINCT ...) deserves separate mention: it must track distinct values per group rather than a running total, so its memory is proportional to distinct values and it defeats some optimisations. Multiple distinct counts in one query are especially expensive.

And all of this is subordinate to checking the plan's estimate-versus-actual row counts first. If the planner expected a thousand groups and got a million, it chose the wrong strategy on bad information, and refreshing statistics may fix the whole thing without any query change.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-20

What may appear in a GROUP BY clause besides a plain column name, and how does portability differ across engines?

Answer

GROUP BY accepts more than column names: expressions, select-list aliases, and ordinal positions. Portability is uneven. PostgreSQL, MySQL, SQLite, BigQuery and Snowflake accept all three. SQL Server and Oracle accept expressions but reject aliases and ordinals: you get an error. The SQL standard only requires column names and expressions; aliases and ordinals are vendor extensions.

Here's the support matrix for current versions:

EngineExpressionAliasOrdinal
PostgreSQL 18YesYesYes
MySQL 8.0YesYesYes
SQL Server 2022YesNoNo
Oracle 19cYesNoNo
SQLite 3.45YesYesYes
BigQueryYesYesYes
SnowflakeYesYesYes

In PostgreSQL, all three forms work:

sql SELECT date_trunc('month', created_at) AS month, COUNT(*) FROM orders GROUP BY 1; -- ordinal -- GROUP BY month; -- alias -- GROUP BY date_trunc('month', created_at); -- expression

The fragility is that alias and ordinal are coupled to the select list. If you add a column before month, GROUP BY 1 now groups by that new column: silently wrong results. If you rename month to order_month, GROUP BY month fails. The expression form survives both changes. Aliases can also be ambiguous: if an alias matches an input column name, PostgreSQL resolves to the input column, which may not be what you intended.

SQL Server and Oracle force you to repeat the expression or use a subquery/CROSS APPLY to name it, then group by that name. That's more verbose but immune to select-list reordering.

My rule: use explicit column names or expressions in GROUP BY. Avoid ordinals in production code. If you use an alias, make it unique and not colliding with any input column. When reviewing a query, flag GROUP BY 1 or GROUP BY alias as a maintenance hazard.

Detection: a query using ordinal will break when the select list changes; you catch it in code review or when tests fail. But silent wrong results are worse: they pass tests if the test data doesn't cover the reorder. So prefer expressions.

Why engines differ: the SQL standard (SQL:2016) defines GROUP BY as column references or expressions. Aliases and ordinals are conveniences some vendors added. PostgreSQL's docs explicitly allow output column names and ordinals, but warn about ambiguity. MySQL allows them even with ONLY_FULL_GROUP_BY. SQL Server and Oracle never added them.

Alternatives: if you need to group by a complex expression and want to name it, use a subquery or CTE: WITH x AS (SELECT date_trunc('month', created_at) AS month, ...) SELECT month, COUNT(*) FROM x GROUP BY month; That works everywhere.

Failure modes: ordinal reorder, alias rename, alias collision, portability break. Detection: code review, static analysis, integration tests against multiple engines if you support them.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-16

How do you aggregate over a date dimension so that periods with no data still appear?

Answer

A GROUP BY over event rows can only produce groups for days that have rows. Days with no activity are simply absent, and absent is not the same as zero. A chart that skips them draws a misleading line, and a table that omits them lets the reader assume continuity.

The fix is to generate the calendar and left join the aggregate onto it, rather than the other way round. In PostgreSQL, generate_series(:start, :end, interval '1 day') produces the dense spine; elsewhere a persisted date dimension table serves the same purpose and is worth having anyway, because it can carry fiscal periods, weekends and holidays that queries otherwise reimplement badly.

SQL
SELECT d.day, COALESCE(SUM(o.amount), 0) AS revenue
FROM generate_series(:start, :end, interval '1 day') AS d(day)
LEFT JOIN orders o
  ON o.created_at >= d.day AND o.created_at < d.day + interval '1 day'
GROUP BY d.day ORDER BY d.day;

Three details matter. The join condition is a half-open range rather than a truncation of the column, which keeps the predicate sargable: writing ON DATE_TRUNC('day', o.created_at) = d.day wraps the column and defeats the index. The COALESCE is required because SUM over the no-match rows returns NULL, not 0, so without it the empty days appear as blanks rather than zeros and the original problem is only half solved. And the series must be generated in the same time zone that defines a day for this report, or the boundaries land in the wrong place.

The same technique extends to grouping by a dimension as well as a date, cross join the calendar with the list of regions to get a dense grid, though at that point the row count multiplies and it is worth checking the consumer actually needs the zeros rather than handling gaps itself.

The last consideration is the current period: today's partial day will always look like a collapse. I either exclude the incomplete period or label it explicitly, because the alternative is a recurring false alarm.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-19

Explain how to compute a running total and a moving average.

Answer

Both are window functions differing only in their frame: the subset of the partition each row's calculation sees.

A running total accumulates from the start of the partition to the current row:

SQL
SUM(amount) OVER (ORDER BY day ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)

A moving average looks back a fixed number of rows:

SQL
AVG(amount) OVER (ORDER BY day ROWS BETWEEN 6 PRECEDING AND CURRENT ROW)

The detail that catches people is ROWS versus RANGE. ROWS counts physical rows; RANGE counts logical values, treating peers, rows tied on the ORDER BY expression, as one unit. With an ORDER BY that has duplicates, the default frame (RANGE UNBOUNDED PRECEDING) includes all tied rows, so a running total jumps to the full day's value on the first row of that day rather than accumulating within it. If you want strict row-by-row accumulation you must say ROWS explicitly. This is the single most common window-frame bug, and it produces plausible-looking output.

The second issue is gaps. 6 PRECEDING with ROWS means six preceding rows, not six days, so if a day is missing, a seven-day moving average silently spans nine calendar days. If the intent is calendar-based, either densify the series first by joining onto a generated calendar, or use a RANGE frame with an interval bound so the window is defined in time rather than in rows.

Third, edge behaviour: the first six rows of a seven-day moving average are computed over fewer rows, so they are noisier and not comparable to the rest. I either exclude them or mark them, rather than charting a ramp that is an artefact of the window filling up.

And if the partition matters, a running total per customer, PARTITION BY resets the accumulation at each boundary, which is almost always what is wanted and easy to omit.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-5

How would you compute several differently-filtered metrics in one query?

Answer

Conditional aggregation. Each aggregate carries its own row filter, and the table is scanned once:

SQL
SELECT customer_id,
       COUNT(*)                                        AS orders,
       COUNT(*) FILTER (WHERE status = 'cancelled')    AS cancelled,
       SUM(amount) FILTER (WHERE status = 'paid')      AS paid_revenue,
       AVG(amount) FILTER (WHERE created_at >= :since) AS recent_average
FROM orders GROUP BY customer_id;

FILTER is standard SQL and states the intent directly. Where it is unavailable, the portable form is a CASE inside the aggregate, but the two aggregates behave differently and this is where bugs come from. With SUM, write SUM(CASE WHEN cond THEN 1 ELSE 0 END). With COUNT, the else branch must yield NULL, not 0, because COUNT counts zeros: COUNT(CASE WHEN cond THEN 1 END). Writing ELSE 0 under COUNT returns the total row count, which looks like a plausible number and is silently wrong.

The alternatives are worse. Separate queries unioned together scan the table once each and need matching shapes. A self-join per status multiplies rows and then requires distinct counting to undo the damage. A correlated subquery per metric evaluates per row and is the slowest of the lot.

The one caveat is that every metric here shares one grouping and one WHERE. If two metrics genuinely need different row scopes, different date ranges over the same grouping, I either widen the WHERE to the union of both scopes and let FILTER narrow each, or compute them separately and join on the grouping key. Widening is usually better, but only while the widened scan stays cheap.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-4

Compare GROUP BY with window functions, and give a case needing both.

Answer

GROUP BY collapses: N rows become one per grouping key, and row detail is gone, which is why every selected expression must be grouped or aggregated. A window function preserves every row and attaches a value computed over a defined set of related rows.

The test is whether you still need the individual rows. 'Revenue per region' collapses: GROUP BY. 'Every order with its region's total and its rank within the region' does not: SUM(amount) OVER (PARTITION BY region) and RANK() OVER (PARTITION BY region ORDER BY amount DESC).

PARTITION BY is the window analogue of GROUP BY; ORDER BY inside OVER establishes sequence for ranking and running totals; and a frame clause narrows the window further, which is how a moving average is expressed.

They combine naturally, and the case where you need both is the classic one: percentage of total per group. Aggregate to one row per product with GROUP BY, then apply a window over those already-aggregated rows to get the overall total on each row, SUM(SUM(amount)) OVER (), and divide. The nested aggregate looks strange but is exactly right: the inner SUM aggregates within the group, the outer window sums across the grouped result. Doing it in one pass avoids a self-join or a scalar subquery re-reading the table.

The evaluation-order consequence is that window results cannot be filtered in WHERE or HAVING, since windows are computed in the SELECT phase after both. Filtering on a rank therefore requires wrapping the query, which is why every top-N-per-group query is nested.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-10

Write a query returning the top three products by revenue within each category.

Answer

This needs two steps: aggregate to one row per product, then rank within category and keep the top three.

SQL
WITH product_revenue AS (
  SELECT category_id, product_id, SUM(amount) AS revenue
  FROM order_lines
  WHERE created_at >= :start AND created_at < :end
  GROUP BY category_id, product_id
),
ranked AS (
  SELECT *, ROW_NUMBER() OVER (
           PARTITION BY category_id ORDER BY revenue DESC, product_id
         ) AS position
  FROM product_revenue
)
SELECT category_id, product_id, revenue
FROM ranked
WHERE position <= 3
ORDER BY category_id, position;

The nesting is forced by evaluation order, not by style: window functions are computed in the SELECT phase, after WHERE and HAVING, so WHERE position <= 3 cannot appear in the same query level that defines position. Wrapping it is the only way to filter on the result.

The ranking function matters. ROW_NUMBER always yields exactly three rows per category, breaking ties arbitrarily, which is why I add product_id as a tiebreaker, so the choice is at least deterministic between runs. RANK returns more than three when there is a tie at third place, and DENSE_RANK numbers ties without gaps. Which is correct depends on whether 'top three' means three rows or all rows at the top three revenue levels: a question worth asking rather than assuming, because stakeholders usually mean the latter and engineers usually write the former.

The half-open date range keeps the filter sargable and avoids the missing-final-day error BETWEEN causes on timestamps. And the aggregation happens before the ranking, since ranking raw order lines would rank individual lines rather than products.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-11

Write a query returning one row per customer with a comma-separated, alphabetically ordered list of the distinct product names they have bought. Name the aggregate, and explain how ordering, duplicates and NULLs are handled.

Answer

In Postgres 18 the aggregate is string_agg, and the ordering is a modifier on the call itself, not on the outer query:

sql SELECT c.id, string_agg(DISTINCT p.name, ',' ORDER BY p.name) AS products FROM customers c JOIN orders o ON o.customer_id = c.id JOIN order_lines ol ON ol.order_id = o.id JOIN products p ON p.id = ol.product_id GROUP BY c.id;

Two things are doing work here. DISTINCT inside the call removes duplicate names before concatenation, and ORDER BY p.name inside the call sorts the values within each group. An outer ORDER BY sorts rows, not the contents of a string, so it cannot give you 'a,b,c' instead of 'c,a,b'.

Postgres is unusual in allowing ORDER BY on any aggregate. Other engines either predate the standard or model ordered aggregation as a separate class:

EngineAggregateOrderingDuplicates
PostgreSQLstring_agg(v, d ORDER BY k)ORDER BY inside the callDISTINCT inside the call
MySQL / MariaDBGROUP_CONCAT(v ORDER BY k SEPARATOR d)ORDER BY inside the call, SEPARATOR keywordDISTINCT inside the call
Oracle, SnowflakeLISTAGG(v, d) WITHIN GROUP (ORDER BY k)WITHIN GROUP clauseLISTAGG(DISTINCT v, d)
SQL ServerSTRING_AGG(v, d) WITHIN GROUP (ORDER BY k)WITHIN GROUP clausenot supported: needs a DISTINCT subquery first

That is why the syntax differs: Oracle and SQL Server treat "aggregate that cares about order" as a distinct category and route it through WITHIN GROUP, while Postgres just lets every aggregate take an ORDER BY.

NULLs. string_agg skips NULL inputs, like every other aggregate. A NULL name contributes nothing: no empty slot, no doubled delimiter. If every value in a group is NULL, the result is NULL, not ''; wrap it in COALESCE(string_agg(...), '') if the consumer needs a string.

The delimiter only goes between values. A group with one row returns that value with no delimiter. A group with zero rows does not exist at all under GROUP BY: there is no row to return. If you need a row for a customer with no orders, drive from customers with a LEFT JOIN to a pre-aggregated subquery, and the aggregate over zero rows yields NULL.

Trace on one group, values ['b', 'a', 'a', NULL]: DISTINCT gives {a, b, NULL}, ORDER BY gives a, b, NULL is dropped, result 'a,b'. One row ['x'] gives 'x'. Zero rows gives NULL.

Failure modes worth naming. In Postgres, string_agg(DISTINCT name, ',' ORDER BY created_at) fails with "in an aggregate with DISTINCT, ORDER BY expressions must appear in argument list": with DISTINCT, the sort key must be the same expression you are deduplicating. In MySQL, group_concat_max_len defaults to 1024 bytes and truncates silently; a long list comes back cut off with no error, so raise it per session or aggregate in a subquery. Postgres has no such cap, but the result is text and a group with millions of rows builds a large value that can spill to disk, and DISTINCT forces a sort or hash per group.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-7

Explain grouping sets, ROLLUP and CUBE, and when they earn their complexity.

Answer

All three compute several grouping levels in one pass. GROUPING SETS enumerates the exact combinations you want. ROLLUP produces the hierarchy: for (region, product) it gives region-and-product, then region, then the grand total, which suits genuinely hierarchical dimensions. CUBE produces every combination, so n columns give 2^n grouping sets.

The alternative is a UNION ALL of near-identical queries, one per level. That scans the table once per branch and duplicates the logic, so a change to the filter has to be made in every branch and eventually is not. The grouping-set form scans once and states the levels declaratively.

The detail that makes them usable is GROUPING(). Subtotal rows carry NULL in the columns not being grouped at that level, which is indistinguishable from a real NULL in the data. GROUPING(column) returns 1 when the NULL marks an aggregated level and 0 when it came from the data, so you can label rows correctly, and, importantly, sort them so subtotals land in the right place rather than sorting among the detail rows.

When they earn it: financial and operational reporting where subtotals are genuinely required, and where the levels are known and stable. When they do not: CUBE over more than three or four columns, where the grouping-set count explodes and most combinations are meaningless to the reader; and any case where the presentation layer or BI tool computes subtotals perfectly well from detail rows, which is common and usually simpler.

My default is to return detail plus one explicit rollup level if the consumer needs it, rather than to emit a fully cubed result the consumer must then filter down.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-17

Explain what an ordered-set aggregate such as a percentile does and when to use one.

Answer

An ordered-set aggregate computes a value that depends on the ordering of the input, not just a running total: percentiles and medians being the common ones. The syntax carries the ordering explicitly: PERCENTILE_CONT(0.95) WITHIN GROUP (ORDER BY duration_ms).

The reason to reach for them is that the mean is a poor summary of any skewed distribution, and almost everything operational is skewed. Average latency is dominated by the bulk of fast requests and hides the tail entirely; a service can have a 40ms average and a 4-second 99th percentile, and it is the second number that describes what users experience and what an SLO must be written against. Averages also make outliers invisible in one direction and disastrous in the other: a single 60-second request barely moves the mean over ten thousand rows.

PERCENTILE_CONT interpolates between values, which suits continuous measures like latency. PERCENTILE_DISC returns an actual value from the data, which is right when the value must be one that genuinely occurred: a real order amount, or a category. MODE() WITHIN GROUP gives the most common value.

The cost caveat is real: exact percentiles require the input to be sorted or fully materialised per group, so memory and time scale with rows per group rather than with group count. On large data this is expensive, and where an approximation is acceptable a sketch-based approximate percentile is dramatically cheaper.

The trap I watch for is averaging percentiles. A p95 computed per shard and then averaged across shards is not the overall p95 and can be badly wrong. Percentiles are not additive: to get an overall percentile you need the combined distribution, which is exactly why quantile sketches that can be merged exist.

In practice I report a percentile alongside a count, because a p99 over eleven rows is noise, and the count is what tells the reader whether to believe it.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-15

How would you count distinct values per group when the data is too large for an exact count, and what do you give up by doing so?

Answer

First I pin down what "too large" means, because that decides the tool. Exact COUNT(DISTINCT x) per group needs memory proportional to the number of distinct values in the largest group, not the row count. A billion rows collapsing into ten groups is fine; 50 million distinct user IDs in one group is not, and that is the case that spills or OOMs. If the distinct sets are small, exact is cheap and I keep it.

When they aren't, I use an approximate distinct aggregate: APPROX_COUNT_DISTINCT in BigQuery and Snowflake, approx_count_distinct in Spark and DuckDB, approx_distinct in Trino. PostgreSQL core has no built-in one; you get it from the postgresql-hll extension or compute it elsewhere. All of these are HyperLogLog: hash each value, track the maximum number of leading zero bits seen per register, and estimate cardinality from the register distribution.

Error is a property of the register count m: standard error is about 1.04/sqrt(m). m = 16,384 registers gives ~0.81%. Spark's default relativeSD is 0.05, i.e. 5%, and you lower it by paying memory. BigQuery documents ~1% typical. The error is relative to the true cardinality, so 1% on 10M distinct users is ±100k.

What you give up, concretely:

  • Reproducibility. Vendors document approximate aggregates as non-deterministic: the same query on unchanged data can return a different number on a rerun, because the hash seed and the partition/merge order are not part of the contract. You cannot diff two runs, assert equality in a test, or put the number in billing.
  • Additivity. Distinct counts do not sum. Per-day distinct users added across a week overcounts anyone active twice. HLL sketches do merge, by union of registers, which is the real reason to store the sketch rather than the number: daily sketches roll into weekly without rescanning events.
  • Exactness at the boundary. Relative error is fine at 10M and meaningless at 12. If a group has 5 distinct values, 5% error is a different answer.
Exact COUNT(DISTINCT)HyperLogLog
MemoryO(distinct per group)O(2^p) per group, ~16 KB at p=14
Error0~1.04/sqrt(m), 0.8% at m=16k
Reproducibleyesno, documented non-deterministic
Mergeable over timeno, must rescanyes, register union
10M distinct in one groupspill / OOM riskconstant

sql -- BigQuery: ~1% typical error, not reproducible run to run SELECT event_date, APPROX_COUNT_DISTINCT(user_id) AS dau FROM events GROUP BY event_date;

-- Spark SQL: default relativeSD 0.05; 0.01 costs ~25x the registers SELECT event_date, approx_count_distinct(user_id, 0.01) AS dau FROM events GROUP BY event_date;

-- PostgreSQL core has no approximate distinct; hll extension does SELECT event_date, # hll_union_agg(user_hll) AS dau FROM daily_user_hll GROUP BY event_date;

Acceptable: dashboard DAU/MAU, funnel step counts, cardinality estimates for the planner, anything where a 1% wobble does not change a decision. Not acceptable: revenue per paying account, invoice line counts, anything reconciling to the cent, uniqueness checks before a dedupe, or a number a customer can dispute. There I pay for exact COUNT(DISTINCT) on the narrow slice, or precompute exact distincts into a materialized table keyed by day and dimension.

The middle path I actually use: approximate for the big exploratory number, exact for the small set of dimensions that feed money or contracts, and store the sketch wherever I need to roll up over time.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-8

Why does the average of per-group averages differ from the average over the whole table, and how do you write the query that reconciles them?

Answer

The short version: AVG over a set of group averages is an unweighted mean. Every group counts once, whether it holds ten rows or ten million. The overall average is the sum of the values divided by the count of the values, which in grouped form is SUM(group_sum) / SUM(group_count). The weighting term is the group's denominator: the row count for a plain mean, or a weight column such as sessions, exposure or revenue when the metric is already a rate.

Concrete case. Two regions, order value:

regionordersavg order valuetotal
A10$500$5,000
B990$50$49,500

True overall average: 54,500 / 1,000 = $54.50. Average of the two group averages: (500 + 50) / 2 = $275. The dashboard is off by 5x, and it is off in the direction of the small group, because region A gets the same vote as region B despite being 1% of the data.

sql -- wrong: unweighted mean of group means SELECT AVG(avg_value) FROM ( SELECT region, AVG(order_value) AS avg_value FROM orders GROUP BY region ) g;

-- right: carry sum and count, not the mean SELECT SUM(group_sum) / SUM(group_n) AS overall_avg FROM ( SELECT region, SUM(order_value) AS group_sum, COUNT(order_value) AS group_n -- COUNT(col), not COUNT(*) FROM orders GROUP BY region ) g;

Two details that bite. First, AVG(x) ignores NULLs, so its denominator is COUNT(x), not COUNT(*). If order_value is nullable, weighting by COUNT(*) understates the average. Second, in PostgreSQL SUM(bigint) / SUM(bigint) is integer division and truncates: cast one side: SUM(group_sum)::numeric / SUM(group_n).

When the metric is already a ratio, the weight is its denominator, not the row count. Average latency per endpoint weighted by request count:

sql SELECT SUM(avg_ms * requests) / SUM(requests) AS overall_avg_ms FROM endpoint_stats;

Weighting by something other than the denominator answers a different question. Weighting price by revenue gives a revenue-weighted average price, which is legitimate but is not the average price a customer paid. Say which one the stakeholder means before writing it.

Averaging averages is only correct when every group has the same size, then the weights cancel. That is rare outside synthetic data, so treat AVG(AVG(x)) as a smell. The failure mode is a materialized view or BI layer that stores per-group means and averages them at render time; it drifts silently as group sizes change. Detect it by running both forms side by side: they agree only when group counts are equal, so any divergence is the bug, and the size of the divergence tells you how much the number is wrong.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-3

A revenue total is too high after a join was added. Diagnose and fix it.

Answer

The hypothesis is join fan-out: the added table matches more than once per parent row, duplicating the parent, so a SUM of a parent-side column counts it once per child.

I confirm before changing anything. Drop the aggregate and compare row counts before and after the join; or group by the parent key and look for counts above one. That takes seconds and distinguishes fan-out from an actual data change, which matters because the fixes are completely different.

The fix depends on what the join is for. If it exists only to test that a related row exists, 'customers who have placed an order', I replace it with EXISTS, which cannot duplicate anything. If I need a value from the child, I pre-aggregate: a CTE reducing the child to one row per parent key, then join to that. If I need the count of parents rather than of joined rows, COUNT(DISTINCT parent.id) is correct. If I need both parent totals and child detail, I first restore the intended grain, for example by pre-aggregating the child, and may then use window functions for row-preserving calculations. A window over an already duplicated join does not repair fan-out.

What I will not do is add SELECT DISTINCT. It makes the number look right in the demo and is wrong the moment two legitimately different child rows project identical columns, and it leaves nothing explaining why it is there, so the next person cannot tell whether removing it is safe.

Afterwards I reconcile: the corrected total should match an independently computed figure. The same sum without the join, or a known control total. A fix that has not been reconciled against a second source is a guess.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-25

Explain the difference between COUNT over a joined result and the count a stakeholder asked for.

Answer

The gap is almost always about grain: which thing is being counted, and at what level of detail the rows sit after the joins.

'How many customers ordered last month' has customers as its grain. If I join customers to orders and count, each customer contributes one row per order, so COUNT(*) counts orders and COUNT(customers.id) counts them just as many times. Only COUNT(DISTINCT customers.id) answers the question asked. The tell is a customer count exceeding the number of customers: obvious if you know the magnitude, invisible if you do not.

Conversely 'how many orders' after joining orders to order lines fans out by line, so the same distinct-counting correction is needed one level down.

And 'how many customers have no orders' inverts it: that is an anti-join (a LEFT JOIN with WHERE orders.id IS NULL, or NOT EXISTS) and a naive count over an inner join cannot express it at all, because the rows simply are not there to count.

So my method is to establish the grain before writing anything: name the entity being counted, then ensure the query either keeps one row per that entity or counts distinctly over its key. When a query has several joins, I check the grain after each one, since each join is an opportunity to change it silently.

The other thing I clarify with the stakeholder is what qualifies. 'Customers who ordered': does a cancelled order count? A refunded one? A free order? A test account? These are not SQL questions and cannot be inferred from the schema, and getting them wrong produces a number that is technically correct against an unstated definition and wrong against the intended one. I write the agreed definition down next to the query, because six months later nobody will remember, and the number will be compared against a differently-defined one and the discrepancy investigated from scratch.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-18

How would you detect and quantify duplicate rows before they corrupt an aggregate?

Answer

Detection is itself a grouping problem: group by the business key and keep groups with more than one row.

SQL
SELECT external_id, COUNT(*) AS copies
FROM orders GROUP BY external_id HAVING COUNT(*) > 1
ORDER BY copies DESC;

This must be HAVING rather than WHERE, since it tests an aggregate. To quantify the impact rather than just list offenders, I compare COUNT(*) with COUNT(DISTINCT external_id) over the whole table: the difference is the number of excess rows, which tells me immediately whether this is a handful of edge cases or a systemic ingestion problem, and therefore whether it is a data fix or a pipeline fix.

The most common reason a duplicate hunt comes back empty when duplicates plainly exist is that the key needs normalising. Grouping on the raw column misses values differing only in case, surrounding whitespace or formatting, so I group on the normalised expression, LOWER(TRIM(external_id)), when the business key is textual.

It is also worth distinguishing three different things people call duplicates: exact duplicate rows, which are usually an ingestion replay; rows sharing a business key but differing in other columns, which are usually updates that were inserted rather than merged and need a survivorship decision; and rows that are legitimately distinct but get double-counted by a join, which is fan-out and not a data problem at all. They have different fixes, and treating fan-out as a data-quality issue sends people cleaning data that is fine.

For prevention rather than detection, the durable fix is a unique constraint on the business key, plus idempotent upserts on the write path so replays converge instead of accumulating. Cleaning duplicates without adding the constraint guarantees they come back.

And I run the detection query on a schedule as a data-quality check rather than only when a number looks wrong, since the whole difficulty with duplicates is that the resulting aggregate looks entirely plausible.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-21

How would you aggregate across multiple currencies correctly?

Answer

Summing a mixed-currency amount column produces a meaningless number, and nothing in the database will warn you: the types are compatible, so it just adds them. That is the first thing to check when a revenue figure looks odd in a business operating in several markets.

The design has three parts.

Store both the original and the converted value. The transaction's own currency and amount are the source of truth and must never be lost, because an audit or a dispute needs the amount actually charged. Alongside them I store the converted amount, the rate used and the rate's effective date. Converting on the fly at read time means the historical report changes every time rates move, which makes reconciliation impossible and quietly rewrites last quarter's numbers.

Pin the rate to the transaction, not to the query. Which rate is correct depends on the accounting policy (transaction-date, month-end, or an average) so the policy is a stated decision, and the chosen rate is recorded on the row so any total can be traced back to how it was computed.

Use exact numerics throughout, and be deliberate about when rounding happens. Converting each row and then summing gives a different total from summing and then converting, because of accumulated per-row rounding. Neither is wrong in principle, but the two disagree by amounts large enough for finance to notice, so the order must be fixed and documented. I round once at presentation where possible, keeping full precision through the aggregation.

Minor-unit handling matters too: currencies have different decimal places, and some have none, so a scale hard-coded at two is wrong for several currencies.

And I present the currency with the number, always. A total labelled only 'revenue' invites exactly the mixed-currency mistake this design exists to prevent, and where a breakdown is genuinely needed, grouping by currency alongside the converted total lets a reader see the composition rather than trusting a single converted figure.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-6

A grouped query was fast in staging and is slow in production. What do you investigate?

Answer

I start from EXPLAIN ANALYZE on production-like data, because the difference is almost always data-shaped rather than code-shaped.

Group cardinality first. Aggregation is typically a hash aggregate: a hash table with one entry per group. Staging might have two hundred groups and production two million. When that table exceeds working memory it spills to disk, and the query does not degrade gracefully: it falls off a cliff. The plan shows the spill directly. Remedies are grouping on fewer or narrower columns, filtering harder before grouping, raising working memory for that session if the query is important and occasional, or pre-aggregating.

Then the row volume reaching the aggregate. A predicate that was selective in staging may not be in production, so far more rows are scanned and grouped. This is where I check the estimate-versus-actual row gap in the plan: a large mismatch means the planner chose its strategy on bad information, often stale statistics or a correlated predicate it cannot model.

Then sargability and index support. A predicate wrapping the column in a function, WHERE DATE_TRUNC('month', created_at) = ..., cannot use an index, which is survivable on a small table and fatal on a large one. Rewriting as a half-open range restores the index. An index matching the grouping or ordering columns can also let the engine use a group aggregate over an ordered scan instead of hashing everything.

Then fan-out, which is a cost problem as well as a correctness one: an unnoticed fan-out multiplies the rows being aggregated.

If after all that the query genuinely must aggregate millions of rows for a dashboard, the answer is architectural rather than a tuning change: a materialized view or an incremental rollup refreshed on a schedule, with the staleness window stated. Then I re-measure at production volume, because a fix validated on staging data has not been validated.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-9

When should aggregation be precomputed rather than run on demand?

Answer

The decision is a ratio: how often the result is read against how often the inputs change, weighted by how expensive the computation is and how much staleness the consumer can accept.

Live aggregation is right when the query is cheap, when reads are infrequent, or when the answer must be exactly current: an account balance shown before a payment, or anything a user acts on immediately.

Precomputation is right when an expensive aggregation is read far more often than its inputs change. The canonical case is a dashboard: millions of rows aggregated, viewed hundreds of times an hour, over data that changes hourly. Computing it per view repeats identical work.

The forms, in increasing complexity. A materialized view refreshed on a schedule is simplest: one definition, one refresh command; the caveat is that a non-concurrent refresh takes a lock, so a concurrent refresh needs a unique index on the view. A rollup table maintained incrementally is more work but avoids recomputing history: each period's aggregate is written once and never recalculated, which is the only thing that scales when history is large. Streaming or trigger-maintained aggregates give near-real-time totals at the cost of write amplification and a genuinely harder correctness problem, since every write path must maintain them.

Whatever the form, three things must be explicit. The staleness window, stated to the consumer: a dashboard showing 'as of 04:00' is honest; one silently showing four-hour-old data as current is not. A backfill and recovery path, because a missed refresh must be repairable. And a reconciliation check comparing the precomputed value against a live recomputation on a sample, because a rollup that silently drifts from its source is worse than no rollup, and incremental maintenance drifts most readily on late-arriving or corrected data.

My default is the simplest form that meets the freshness requirement, and I escalate only when measurement shows it is insufficient.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-13

How would you build a daily metrics rollup that tolerates late-arriving data?

Answer

The naive incremental rollup (aggregate yesterday once, append it, never look back) is wrong the moment a row arrives late or is corrected, and it is wrong silently and permanently.

So the design starts by distinguishing two timestamps. Event time is when the thing happened; ingestion time is when the row landed. A rollup keyed on event time but selected by ingestion time is what makes late data tractable: I can ask 'which rows arrived since my last run, and which event days do they affect'.

The pattern I use is idempotent recomputation over a bounded window. Each run recomputes complete days rather than appending deltas, and writes them with an upsert keyed on the day, so re-running is harmless. The window covers the last N days, where N is chosen from the measured lateness distribution, if 99.9% of rows arrive within two days, a rolling seven-day recompute is comfortable. Days older than the window are closed, and a correction reaching one of them is handled by an explicit backfill for those specific days rather than by widening the window forever.

That idempotency is the property that matters operationally: a failed run is simply re-run, a deploy mid-run is safe, and a backfill uses the same code path as the regular job rather than a separate script that will rot.

I record a watermark per rollup row, the maximum ingestion time included, so consumers can tell what a number is based on, and a recomputed row can be distinguished from a stale one.

For correctness I run a periodic reconciliation comparing the rollup against a live recomputation over a sample of days, and alert on any divergence. Incremental aggregation drifts, and drift that nobody checks for is discovered by a stakeholder rather than by the team.

Finally I make the staleness visible in the presentation, 'as of' with the watermark, because a dashboard that presents partial recent data as final is the failure people actually get burned by, since today's incomplete day always looks like a decline.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-23

When is it correct to aggregate in the application rather than in the database?

Answer

The default is the database, for a straightforward reason: aggregation reduces data, and doing it where the data lives means transferring the small result instead of the large input. Pulling a million rows into the application to sum them wastes network bandwidth, serialisation time and application memory to compute something the database would do in one pass with an optimised operator. It is also where the indexes are.

Application-side aggregation is justified in a few specific cases. When the rows have already been fetched for another purpose and aggregating them is free: computing a total over a page of results you are rendering anyway. When the computation is genuinely not expressible in SQL, or expressible only tortuously: complex business rules, calls to external services, or logic that already exists as well-tested application code and would be risky to duplicate in SQL. When the data spans several systems and must be combined outside any one of them. And when the aggregation is over a small, bounded set where the difference is irrelevant and the application code is clearer.

The anti-pattern to name is the N+1 aggregate: fetching a list, then issuing a query per row to compute its total. That is 1+N round trips where a single grouped query would do, and it is slow in a way that scales linearly with data, so it passes review and fails in production.

The honest caveat on the other side is that pushing everything into SQL can produce enormous unmaintainable queries encoding business logic nobody can test or read. There is a real trade-off between execution efficiency and comprehensibility, and I would rather have a slightly slower query that the team can reason about than a virtuosic one that nobody dares change.

So my rule: aggregate in the database by default, especially when it reduces the row count materially; move it to the application when the logic genuinely does not belong in SQL or when the data is already in hand, and never issue a query per row to do it.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-22

Explain what makes an aggregation query testable, and how you would test one.

Answer

What makes it testable

Three properties, none of them about syntax.

  1. It lives in one named artefact that production also runs: a view, a repository method, a dbt model. If the dashboard holds its own pasted copy, the test proves nothing about what ships.
  2. Its inputs are fully determined by the test: no NOW(), no CURRENT_DATE, no sampling. The date range is a parameter. A query that reads the clock cannot have a fixed expected value, and a test without one is a smoke test.
  3. The fixture contains the cases that separate a correct query from a plausible wrong one. Aggregation defects return a believable number rather than an error, so the fixture is the assertion.

The fixture

order_idcustomer_idstatusamountcreated_at
1011 Alicepaid100.002024-03-31 23:59:59
1021 Alicepaid50.002024-04-01 00:00:00
1031 Alicerefunded30.002024-04-02 12:00:00
1042 BobpaidNULL2024-04-02 09:00:00
1052 Bobpaid20.002024-04-03 09:00:00
1064 DavepaidNULL2024-04-03 10:00:00
1071 Alicepaid75.002024-04-30 23:59:59

Customer 3 (Carol) has no orders at all.

The query (PostgreSQL 16 semantics)

SQL
CREATE VIEW paid_revenue_by_customer AS
SELECT o.customer_id,
       SUM(o.amount) AS paid_total
FROM orders o
WHERE o.status = 'paid'
  AND o.created_at >= TIMESTAMP '2024-04-01 00:00:00'
  AND o.created_at <  TIMESTAMP '2024-05-01 00:00:00'
GROUP BY o.customer_id;

Expected output, computed by hand from the fixture

customer_idpaid_total
1125.00
220.00
4NULL

No row for customer 3. Four distinct outcomes from one query: a normal sum, a sum that skipped a NULL, a NULL-only group, and an absent group. That spread is the point: assert these exact values, never paid_total > 0, which passes for almost every wrong query.

What each wrong variant produces

  • BETWEEN '2024-04-01' AND '2024-04-30': against a timestamp column the upper bound is <= 2024-04-30 00:00:00, so order 107 is dropped and Alice reads 50.00 instead of 125.00. The half-open range is the fix.
  • Joining to order_items before the SUM: order 102 has 3 items, so Alice's 50.00 is counted three times: 150.00 + 75.00 = 225.00 instead of 125.00. Fan-out multiplies every measure by the child count.
  • COALESCE(SUM(amount), 0): Dave reads 0.00, identical to Carol's 0.00 under a LEFT JOIN. "No paid orders" and "paid order with unknown amount" collapse into the same row.
  • HAVING SUM(amount) > 0: NULL > 0 is NULL, not true, so Dave's group is dropped silently. Alice 125.00, Bob 20.00, Dave gone.

Boundary cases, asserted separately from the main case

Zero matching rows (SUM returns NULL, not 0), exactly one row, an all-NULL measure column, a group whose only rows are removed by the status predicate, and a duplicate business key if duplicates are possible in production.

Plan shape, not wall clock

SQL
-- seed enough rows that the index is the cheaper plan, then:
ANALYZE orders;
EXPLAIN (FORMAT JSON) SELECT ... ;

Assert the plan contains no "Node Type": "Seq Scan" on orders. Seed the table and run ANALYZE first: on a small table the planner picks a seq scan and the test fails for the wrong reason. Never assert on elapsed time in CI.

Reconciliation

For anything reported externally, compare the aggregate against a control total computed by a different path, sum the raw payment events in a separate query or engine, and assert exact equality on integer cents. That is the only check that catches a query which is internally consistent and conceptually wrong.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-24

Describe how you would design the aggregation layer for a customer-facing analytics feature.

Answer

Customer-facing changes the requirements, because the aggregation now needs multi-tenant isolation, bounded latency for every tenant, and stated freshness: none of which an internal dashboard needs.

Isolation first. Every query must be scoped by tenant, and that scoping must be enforced structurally: row-level security, or a data-access layer where the tenant predicate cannot be omitted: rather than by each query author remembering. A cross-tenant leak in an analytics feature is a serious breach, and aggregate queries are unusually easy to get wrong here because a forgotten predicate still returns a plausible number.

Tenant skew is the defining technical problem. Tenant size distributions are extremely skewed: the largest tenant may have thousands of times the data of the median. A design tested on median tenants falls over on the largest, and a shared precomputation strategy sized for the median gives the biggest customer the worst experience. So I size against the largest tenants and consider tiered strategies: live aggregation for small tenants where it is fast and always fresh, precomputed rollups for large ones.

Precomputation with explicit freshness. Recurring queries over slow-changing data get rollup tables keyed by tenant and period, maintained idempotently so re-runs and backfills are safe, with a watermark per row. The UI states 'as of', because a customer comparing your figure to their own system needs to know what window it covers, and the incomplete current period must be labelled or excluded, since it always looks like a collapse.

Bounded work per request. Statement timeouts, mandatory date bounds with a maximum span, pagination on any detail drill-down, and a cap on grouping cardinality so nobody can request a group-by that returns a million rows. Without these, one customer's ad-hoc request degrades everyone's.

Isolation from the transactional path. Replicas or a separate analytical store, so an expensive analytics query cannot slow down the product's write path.

Correctness as a product property. Definitions documented in the UI, so the customer knows what 'active user' means; reconciliation checks comparing rollups against live recomputation on a sample; and versioned definitions, because changing a metric's meaning silently is something customers notice and lose trust over. If a definition must change, I would surface it rather than let numbers shift underneath them.

I would start with live aggregation against a replica plus hard limits, measure real tenant distributions, and introduce precomputation where measurement shows it is needed: rather than building the rollup infrastructure first for a load that may not materialise.

Curated: · Written: · Reviewed:

Difficulty: Hard