0
0
PostgreSQLquery~20 mins

Date arithmetic with intervals in PostgreSQL - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Date Arithmetic Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
query_result
intermediate
2:00remaining
Calculate date after adding interval
What is the result of this query?
SELECT DATE '2024-01-15' + INTERVAL '10 days';
PostgreSQL
SELECT DATE '2024-01-15' + INTERVAL '10 days';
A2024-01-15 10:00:00
B2024-01-25
C2024-01-05 00:00:00
D2024-01-25 00:00:00
Attempts:
2 left
💡 Hint
Adding an interval to a date returns a timestamp with time set to midnight.
query_result
intermediate
2:00remaining
Subtract interval from timestamp
What is the output of this query?
SELECT TIMESTAMP '2024-06-01 15:30:00' - INTERVAL '3 hours 15 minutes';
PostgreSQL
SELECT TIMESTAMP '2024-06-01 15:30:00' - INTERVAL '3 hours 15 minutes';
A2024-06-01 18:45:00
B2024-06-01 12:15:00
C2024-06-01 15:15:00
D2024-06-01 03:15:00
Attempts:
2 left
💡 Hint
Subtracting an interval reduces the timestamp by that amount.
📝 Syntax
advanced
2:00remaining
Identify the syntax error in interval addition
Which option will cause a syntax error when adding an interval to a date in PostgreSQL?
ASELECT DATE '2024-03-10' + '1 month';
BSELECT DATE '2024-03-10' + INTERVAL '1 month';
CSELECT DATE '2024-03-10' + INTERVAL '30 days';
DSELECT DATE '2024-03-10' + INTERVAL '1 year';
Attempts:
2 left
💡 Hint
Intervals must be explicitly cast or written with INTERVAL keyword.
optimization
advanced
2:00remaining
Optimize interval addition for multiple rows
Given a table events(event_date DATE), which query is more efficient to add 7 days to all event_date values?
ASELECT event_date + INTERVAL '7 days' FROM events;
BSELECT event_date + INTERVAL '168 hours' FROM events;
CSELECT event_date + INTERVAL '1 week' FROM events;
DSELECT event_date + INTERVAL '7 days 0 hours' FROM events;
Attempts:
2 left
💡 Hint
Using standard interval units can help the query planner optimize better.
🧠 Conceptual
expert
2:00remaining
Understanding interval multiplication and addition
What is the output of this query?
SELECT DATE '2024-01-01' + INTERVAL '1 day' * 3;
PostgreSQL
SELECT DATE '2024-01-01' + INTERVAL '1 day' * 3;
A2024-01-04 00:00:00
B2024-01-03 00:00:00
C2024-01-01 03:00:00
DError: cannot multiply interval by integer
Attempts:
2 left
💡 Hint
Multiplying an interval by an integer repeats the interval that many times.