Scenario: Streamhub's analytics team is reviewing platform activity at a daily level to identify high-traffic days.
Task: Write a query to return each calendar day and the total number of events recorded on that day.
Assumptions:
- The
eventstable holds one row per recorded event, with the timestamp stored inoccurred_at. - A calendar day is identified by its date and covers every event recorded within that day.
Output:
- One row per calendar day present in the data.
- Columns in this order:
day,event_count.
Schema · analytics 5 tables
Run previews · Check grades
Write a query, then run it to see results here.
Worked solution Try it yourself first
SELECT
DATE_TRUNC('day', occurred_at)::date AS DAY,
COUNT(*) AS event_count
FROM
events
GROUP BY
DATE_TRUNC('day', occurred_at) The shape
date_trunc('day', occurred_at) reduces each event timestamp to midnight of its calendar day, which makes every event from the same day share one grouping key. COUNT(*) then runs once per day and returns one row per calendar day with the event volume for that day.
Clause by clause
SELECT date_trunc('day', occurred_at)::date AS day, COUNT(*) AS event_countreturns one row per day. The::datecast removes the midnight time component so the output column types as a date instead of a timestamp.COUNT(*)counts the events that fall inside the day.FROM eventsreads every recorded event. There is noWHERE; every day with at least one event is in scope.GROUP BY date_trunc('day', occurred_at)uses the same truncation as the grouping key. Two events recorded at14:32and22:05on the same date both truncate to that date at midnight and end up in the same group.
The trap
The GROUP BY has to repeat the date_trunc expression rather than reference the day alias. The alias defined in SELECT is not yet in scope when GROUP BY is evaluated, so GROUP BY day raises an error. Repeat the expression, or write GROUP BY 1 to reference the first SELECT column by position.
You practiced truncating a timestamp to its calendar day so all events sharing a day collapse into a single row.