0
0
MySQLquery~20 mins

DATE_ADD and DATE_SUB in MySQL - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Date Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
query_result
intermediate
2:00remaining
What is the output of this DATE_ADD query?
Given the table events with a column event_date of type DATE, what will be the result of this query?

SELECT DATE_ADD('2024-06-15', INTERVAL 10 DAY) AS new_date;
MySQL
SELECT DATE_ADD('2024-06-15', INTERVAL 10 DAY) AS new_date;
A2024-06-05
B2024-06-25
C2024-07-15
D2024-06-16
Attempts:
2 left
💡 Hint
Think about adding 10 days to June 15, 2024.
query_result
intermediate
2:00remaining
What does this DATE_SUB query return?
Consider the query:

SELECT DATE_SUB('2024-01-01', INTERVAL 1 MONTH) AS previous_month;

What is the output?
MySQL
SELECT DATE_SUB('2024-01-01', INTERVAL 1 MONTH) AS previous_month;
A2023-12-31
B2023-11-01
C2023-12-30
D2023-12-01
Attempts:
2 left
💡 Hint
Subtracting one month from January 1, 2024 goes to December 2023. Check the day part carefully.
📝 Syntax
advanced
2:00remaining
Which query correctly adds 2 hours to a datetime value?
You want to add 2 hours to the datetime '2024-06-15 10:00:00'. Which of these queries is syntactically correct and returns the expected result?
ASELECT DATE_ADD('2024-06-15 10:00:00', INTERVAL 2 HOUR);
BSELECT DATE_ADD('2024-06-15 10:00:00', 2 HOURS);
CSELECT DATE_ADD('2024-06-15 10:00:00', INTERVAL '2' HOUR);
DSELECT DATE_ADD('2024-06-15 10:00:00', INTERVAL 2 HOURS);
Attempts:
2 left
💡 Hint
Check the syntax for INTERVAL and the unit name.
optimization
advanced
2:00remaining
Optimizing date subtraction in a WHERE clause
You want to select all records from orders where order_date is within the last 30 days. Which query is the most efficient?
ASELECT * FROM orders WHERE order_date >= DATE_SUB(CURDATE(), INTERVAL 30 DAY);
BSELECT * FROM orders WHERE DATE_SUB(order_date, INTERVAL 30 DAY) >= CURDATE();
CSELECT * FROM orders WHERE order_date >= CURDATE() - INTERVAL 30 DAY;
DSELECT * FROM orders WHERE order_date BETWEEN DATE_SUB(CURDATE(), INTERVAL 30 DAY) AND CURDATE();
Attempts:
2 left
💡 Hint
Think about how indexes work with functions on columns.
🧠 Conceptual
expert
2:00remaining
What is the result of this complex date arithmetic?
Consider this query:

SELECT DATE_ADD(DATE_SUB('2024-03-31', INTERVAL 1 MONTH), INTERVAL 1 MONTH) AS result_date;

What is the value of result_date?
MySQL
SELECT DATE_ADD(DATE_SUB('2024-03-31', INTERVAL 1 MONTH), INTERVAL 1 MONTH) AS result_date;
A2024-03-31
B2024-02-29
C2024-03-29
D2024-03-01
Attempts:
2 left
💡 Hint
Subtracting one month from March 31, 2024, then adding one month back may not return the original date.