Working with dates
SQL · 16 questions
Short notes
Key idea
Dates let you filter by period, group by month and measure gaps. The main tools are pulling out a part, rounding down to a period, and doing arithmetic with intervals.
Syntax
EXTRACT(YEAR FROM order_date) -- 2024
EXTRACT(DOW FROM order_date) -- 0 = Sunday
date_trunc('month', order_date) -- 2024-03-01 00:00
order_date + INTERVAL '7 days'
ship_date - order_date -- days between two dates
Example
Orders per month:
SELECT date_trunc('month', order_date) AS month, COUNT(*) AS orders
FROM orders
GROUP BY 1
ORDER BY 1;
Traps
EXTRACT(MONTH ...)alone mixes years: March 2023 and March 2024 land in the same group. Usedate_truncinstead.- Filter ranges with
>=start and<next start, so timestamps late on the last day aren't lost. - Subtracting two timestamps gives an interval, not a number of days.
- Adding a year to 29 February lands on 28 February.
Want the full lesson with step-by-step examples, a project and a certificate? SQL course, ₹120 →
- Question 1easy
In DuckDB, what does
DATE_TRUNC('month', DATE '2024-02-29')return? - Question 2medium
7 orders were placed in February 2024 and 2 in February 2023. What does this return?
SELECT COUNT(*) FROM orders WHERE EXTRACT(month FROM order_date) = 2;
- Question 3medium
What does this return?
SELECT MAX(shipped_date - order_date) FROM orders;
- Question 4hard
What is
DATE '2024-02-29' + INTERVAL 1 YEAR? - Question 5medium
What is
DATE '2024-01-31' + INTERVAL 1 MONTHin DuckDB?
Working with dates
Working with dates
Working with dates
Working with dates
Working with dates
11 more questions on this topic, with hints, and tests
Sign up free for 21 days of every question and test.