An online grocer's eight baskets in a pilot region have values 12, 15, 18, 22, 30, 41, 55 and 1,007. In PostgreSQL, what do PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY v), PERCENTILE_DISC(0.5) WITHIN GROUP (ORDER BY v) and AVG(v) return, and which best describes a typical basket?
Show the answer and explanation
Correct answer: B, 26, 22 and 150: CONT interpolates between the 4th and 5th values, DISC returns the first value whose cumulative share reaches 0.5, and the median describes a typical basket.
Explanation SQL
Both are ordered-set aggregates, but they differ when the percentile falls between two rows:
- PERCENTILE_CONT(0.5) treats the data as continuous and interpolates. With 8 values the median lies halfway between the 4th (22) and 5th (30) values: (22 + 30) / 2 = 26.
- PERCENTILE_DISC(0.5) returns an actual input value: the first one whose cumulative share reaches 0.5. The 4th of 8 values has a cumulative share of 4/8 = 0.5, so it returns 22.
- AVG = (12 + 15 + 18 + 22 + 30 + 41 + 55 + 1,007) / 8 = 1,200 / 8 = 150.
The mean of 150 is larger than seven of the eight baskets, because one large order pulls it up. On right-skewed data such as basket values, income or latency, the median and percentiles such as p90 describe the typical case. The mean is still the right input for totals (revenue = mean × count).
| Function | Interpolates? | Can return a value not in the data? |
|---|---|---|
| PERCENTILE_CONT | yes | yes (26 here) |
| PERCENTILE_DISC | no | no (22 here) |
In BigQuery, PERCENTILE_CONT and PERCENTILE_DISC are analytic functions used with OVER (), and APPROX_QUANTILES(v, 100)[OFFSET(50)] is the usual approximate median for large tables.
Why the other answers fail: swapping CONT and DISC is the classic mix-up. DISC does not move up to the upper middle value (30); it stops at the first value whose cumulative share is at least 0.5. Using every value is exactly why the mean is not typical here.
Interview tip: when reporting skewed metrics, give median and p90 alongside the mean, and say which percentile function you used so others can reproduce the number.