Chapter 5 · Lesson 2 of 3

Extracting Parts of a Date

Pull the year, month, or day out of a date with EXTRACT, then group by the extracted part to count how many orders arrived per month.

You can pull specific parts out of a date with EXTRACT.

For example, to get the month number from order_date:

SELECT EXTRACT(MONTH FROM order_date) AS order_month
FROM orders

This is useful when you want to group by year, month, quarter, weekday, and more. Be careful when grouping by month number alone: January 2024 and January 2025 would both become month 1.

For real month-based reports, DATE_TRUNC is often safer because it keeps the year and month together by rounding the date down to the start of the month.

SELECT DATE_TRUNC('month', order_date) AS month_start
FROM orders

Sample data

This lesson loads the orders table (7 rows) into DuckDB in your browser with one click, so you can run every example without uploading anything.

Setup SQL for orders
CREATE OR REPLACE TABLE orders (
    order_id INTEGER,
    customer_name VARCHAR,
    order_date DATE,
    ship_date DATE,
    amount DECIMAL(10,2)
  );

INSERT INTO orders VALUES
    (1, 'Alice', '2024-01-03', '2024-01-05', 1200),
    (2, 'Bob', '2024-01-15', '2024-01-20', 850),
    (3, 'Charlie', '2024-02-01', '2024-02-04', 640),
    (4, 'Diana', '2024-02-18', '2024-02-25', 430),
    (5, 'Eve', '2024-03-02', '2024-03-03', 1500),
    (6, 'Frank', '2024-03-28', '2024-04-02', 920),
    (7, 'Grace', '2024-04-10', '2024-04-15', 760);

Practice challenge

Count how many orders were placed in each month. Return order_month and order_count, ordered by order_month.

Hint: Use EXTRACT(MONTH FROM order_date), GROUP BY the same expression, and COUNT(*).

Run your query in the editor and the lesson checks the result automatically.

Open this lesson in the SQL editor

Lessons in Working with Dates

Filter by date ranges, extract parts of dates, and calculate the days between two dates in DuckDB SQL.

  1. 01 · Filtering by Date Ranges
  2. 02 · Extracting Parts of a Date
  3. 03 · Date Arithmetic with DATE_DIFF

Related guides