0
0
PostgreSQLquery~20 mins

DATE_TRUNC for rounding dates in PostgreSQL - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Date Truncation Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
query_result
intermediate
1: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');
A2024-06-15 14:00:00
B2024-06-15 14:37:00
C2024-06-15 00:00:00
D2024-06-15 15:00:00
Attempts:
2 left
💡 Hint
Think about what 'truncating to hour' means: it resets minutes and seconds to zero.
query_result
intermediate
1: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');
A2024-01-01 00:00:00
B2024-06-15 00:00:00
C2024-06-01 00:00:00
D2024-06-15 14:37:45
Attempts:
2 left
💡 Hint
Truncating to month resets day, hour, minute, and second to the start of the month.
📝 Syntax
advanced
2:00remaining
Identifying invalid DATE_TRUNC usage
Which of the following queries will cause a syntax error in PostgreSQL?
ASELECT DATE_TRUNC('year', TIMESTAMP '2024-06-15 14:37:45');
BSELECT DATE_TRUNC('minute', '2024-06-15 14:37:45'::timestamp);
CSELECT DATE_TRUNC('week', TIMESTAMP '2024-06-15 14:37:45');
DSELECT DATE_TRUNC('fortnight', TIMESTAMP '2024-06-15 14:37:45');
Attempts:
2 left
💡 Hint
Check if the first argument to DATE_TRUNC is a valid date part.
optimization
advanced
2: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?
ASELECT created_at::date AS day, COUNT(*) FROM orders GROUP BY day ORDER BY day;
BSELECT DATE_TRUNC('hour', created_at) AS day, COUNT(*) FROM orders GROUP BY day ORDER BY day;
CSELECT created_at, COUNT(*) FROM orders GROUP BY created_at ORDER BY created_at;
DSELECT DATE_TRUNC('day', created_at) AS day, COUNT(*) FROM orders GROUP BY day ORDER BY day;
Attempts:
2 left
💡 Hint
Casting to date is simpler and faster than truncating timestamps for daily grouping.
🧠 Conceptual
expert
2: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');
A2024-06-15 00:00:00+00
B2024-06-14 00:00:00+00
C2024-06-15 21:00:00+00
D2024-06-16 00:00:00+00
Attempts:
2 left
💡 Hint
Remember that TIMESTAMPTZ values are stored in UTC internally and DATE_TRUNC truncates in the session time zone.