Vibe Interview team
SQL interview question: average price within three days of an observation
At a technical interview on 28 April 2026, the candidate was asked to average competitors’ prices within three days on either side of a date. The question appears at 02:11 in the interview archive. The schema, sample data and solution below are our own worked example.
What counts as one observation?
Assume each row records one competitor price for an item on a date. For each row, return the average of all recorded prices for that item from three days before through three days after, inclusive. A missing observation contributes nothing. Ask whether each quote or each competitor should have equal weight.
Use a calendar interval in PostgreSQL
Here observed_on is a DATE and price is a non-null numeric value. PARTITION BY keeps items separate. RANGE uses the distance between dates. A ROWS frame would count neighbouring records, even if they were weeks apart.
SELECT item_id, observed_on, price,
AVG(price) OVER (
PARTITION BY item_id
ORDER BY observed_on
RANGE BETWEEN INTERVAL '3 days' PRECEDING
AND INTERVAL '3 days' FOLLOWING
) AS mean_price
FROM competitor_prices
ORDER BY item_id, observed_on;Check one boundary and one gap
For a single item, take three observations in June. On the 4th the window covers the 1st through the 7th. The quote on the 1st counts, the quote on the 8th does not. Two prices contribute, so the answer is (100 + 160) / 2 = 130.
Scroll the table sideways to compare both products.
| Day | Price | Mean |
|---|---|---|
| 1 | 100 | 130 |
| 4 | 160 | 130 |
| 8 | 400 | 400 |
Try a follow-up
What if a competitor reports prices ten times a day? In this query it gets ten votes. If the business wants equal weight per competitor, average the quotes for each competitor in the window first, then average those competitor means. Explain the difference aloud before changing the SQL.