Challenge - 5 Problems
Date Truncation Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ query_result
intermediate1:30remaining
Rounding a timestamp to the start of the hour
Given the timestamp '2024-06-15 14:37:45', what is the result of
DATE_TRUNC('hour', TIMESTAMP '2024-06-15 14:37:45')?PostgreSQL
SELECT DATE_TRUNC('hour', TIMESTAMP '2024-06-15 14:37:45');
Attempts:
2 left
💡 Hint
Think about what 'truncating to hour' means: it resets minutes and seconds to zero.
✗ Incorrect
DATE_TRUNC with 'hour' sets minutes, seconds, and smaller units to zero, keeping only the year, month, day, and hour.
❓ query_result
intermediate1:30remaining
Rounding a timestamp to the start of the month
What is the output of
DATE_TRUNC('month', TIMESTAMP '2024-06-15 14:37:45')?PostgreSQL
SELECT DATE_TRUNC('month', TIMESTAMP '2024-06-15 14:37:45');
Attempts:
2 left
💡 Hint
Truncating to month resets day, hour, minute, and second to the start of the month.
✗ Incorrect
DATE_TRUNC with 'month' returns the first day of the month at midnight.
📝 Syntax
advanced2:00remaining
Identifying invalid DATE_TRUNC usage
Which of the following queries will cause a syntax error in PostgreSQL?
Attempts:
2 left
💡 Hint
Check if the first argument to DATE_TRUNC is a valid date part.
✗ Incorrect
PostgreSQL supports specific date parts like year, month, week, day, hour, minute, second. 'fortnight' is not supported and causes an error.
❓ optimization
advanced2:00remaining
Optimizing queries using DATE_TRUNC for grouping
You want to count the number of orders per day from a table
orders with a created_at timestamp column. Which query is the most efficient and correct?Attempts:
2 left
💡 Hint
Casting to date is simpler and faster than truncating timestamps for daily grouping.
✗ Incorrect
Casting the timestamp to date extracts the date part directly and is more efficient than DATE_TRUNC for grouping by day.
🧠 Conceptual
expert2:30remaining
Understanding DATE_TRUNC behavior with time zones
Consider a timestamp with time zone value '2024-06-15 23:30:00+02'. What is the result of
DATE_TRUNC('day', TIMESTAMPTZ '2024-06-15 23:30:00+02') when run in a session with time zone set to UTC?PostgreSQL
SET TIME ZONE 'UTC'; SELECT DATE_TRUNC('day', TIMESTAMPTZ '2024-06-15 23:30:00+02');
Attempts:
2 left
💡 Hint
Remember that TIMESTAMPTZ values are stored in UTC internally and DATE_TRUNC truncates in the session time zone.
✗ Incorrect
The timestamptz '2024-06-15 23:30:00+02' is equivalent to '2024-06-15 21:30:00+00' in UTC. In a UTC session, DATE_TRUNC('day', ...) truncates it to '2024-06-14 00:00:00+00' because the timestamp is on 21:30 UTC on June 15, so truncating to day gives midnight of June 15 UTC, but the original time is after midnight UTC on June 15, so the truncation is to June 15 00:00:00 UTC. Actually, this needs correction: 23:30+02 is 21:30 UTC on June 15, so truncating to day in UTC is 2024-06-15 00:00:00+00, so option B is correct.