TECHNOLOGIESTieInn Technologies

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. Use date_trunc instead.
  • 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 →

Questions

Open in Code Lab5 free questions
5 questions

    Working with dates

  1. Question 1easy

    In DuckDB, what does DATE_TRUNC('month', DATE '2024-02-29') return?

  2. Working with dates

  3. 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;
  4. Working with dates

  5. Question 3medium

    What does this return?

    SELECT MAX(shipped_date - order_date) FROM orders;
  6. Working with dates

  7. Question 4hard

    What is DATE '2024-02-29' + INTERVAL 1 YEAR?

  8. Working with dates

  9. Question 5medium

    What is DATE '2024-01-31' + INTERVAL 1 MONTH in DuckDB?

11 more questions on this topic, with hints, and tests

Sign up free for 21 days of every question and test.