0
0
SQLquery~20 mins

DATE_FORMAT and EXTRACT in SQL - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Date Mastery Badge
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_FORMAT query?
Given a table events with a column event_date of type DATE, what is the output of the following query?
SELECT DATE_FORMAT(event_date, '%Y-%m-%d') AS formatted_date FROM events WHERE event_id = 1;
SQL
SELECT DATE_FORMAT(event_date, '%Y-%m-%d') AS formatted_date FROM events WHERE event_id = 1;
A'2023/15/07'
B'07/15/2023'
C'15-07-2023'
D'2023-07-15'
Attempts:
2 left
💡 Hint
The format string '%Y-%m-%d' means year-month-day with dashes.
query_result
intermediate
2:00remaining
What does EXTRACT return for this date?
Consider the query:
SELECT EXTRACT(MONTH FROM '2024-02-29'::DATE) AS month_value;

What is the value of month_value?
SQL
SELECT EXTRACT(MONTH FROM '2024-02-29'::DATE) AS month_value;
A2
B29
C2024
DNULL
Attempts:
2 left
💡 Hint
EXTRACT(MONTH FROM date) returns the month number from the date.
📝 Syntax
advanced
2:00remaining
Which query correctly extracts the year from a timestamp?
You want to extract the year from a timestamp column named created_at. Which of the following queries is syntactically correct and returns the year as an integer?
ASELECT EXTRACT('YEAR' FROM created_at) FROM orders;
BSELECT EXTRACT(YEAR FROM created_at) FROM orders;
CSELECT EXTRACT(YEAR, created_at) FROM orders;
DSELECT EXTRACT(created_at, YEAR) FROM orders;
Attempts:
2 left
💡 Hint
EXTRACT uses the syntax EXTRACT(field FROM source). The field is not a string.
optimization
advanced
2:00remaining
Optimizing date filtering with EXTRACT vs DATE_FORMAT
You want to select all rows from sales where the sale happened in March 2023. Which query is more efficient and why?
ASELECT * FROM sales WHERE EXTRACT(YEAR FROM sale_date) = 2023 AND EXTRACT(MONTH FROM sale_date) = 3;
BSELECT * FROM sales WHERE DATE_FORMAT(sale_date, '%Y-%m') = '2023-03';
CSELECT * FROM sales WHERE sale_date >= '2023-03-01' AND sale_date < '2023-04-01';
DSELECT * FROM sales WHERE sale_date LIKE '2023-03%';
Attempts:
2 left
💡 Hint
Filtering by range on the raw date column can use indexes better than functions on the column.
🔧 Debug
expert
2:00remaining
Why does this EXTRACT query raise an error?
Given the query:
SELECT EXTRACT(QUARTER FROM '2023-05-10');

It raises an error. What is the cause?
SQL
SELECT EXTRACT(QUARTER FROM '2023-05-10');
AThe date literal is missing a type cast to DATE or TIMESTAMP.
BThe EXTRACT function requires the date to be in ISO format.
CQUARTER is not a valid field for EXTRACT in SQL.
DThe FROM keyword is not allowed in EXTRACT.
Attempts:
2 left
💡 Hint
Check if the string literal is recognized as a date type by the database.