Tech challenge · SQL
A one-day query scans the whole table
An events table holds two billion rows and is indexed (or partitioned) on created_at. This query for a single day takes minutes and reads everything:
SELECT COUNT(*) FROM events
WHERE DATE(created_at) = '2026-03-01';Why, and what is the fix?
Think it through or sketch an answer first, then open the hint or the solution.
Show a hint
What can the engine do with an index when the column is wrapped in a function?
Show the solution
Wrapping the column in a function makes the predicate non-sargable: the engine has to compute DATE() for every row before it can compare, so it cannot seek the index or prune partitions. Compare the bare column with a half-open range instead.
Example (SQL)
SELECT COUNT(*) FROM events
WHERE created_at >= '2026-03-01'
AND created_at < '2026-03-02';
Common mistakes
- Using BETWEEN '2026-03-01' AND '2026-03-01 23:59:59': it misses fractional seconds before midnight.
- Adding an index on DATE(created_at) everywhere instead of writing a range: it helps one query shape and costs every write.
How did you do? Your answer is saved in this browser and comes back for revision later.