Learn SQL
SQL Date Queries: Date Ranges, EXTRACT, and DATE_DIFF Explained
Date queries become much easier when you filter with clear ranges, extract useful parts, and calculate durations directly in SQL.
On This Page
Dates turn rows into timelines
Dates answer some of the most common business questions: what happened this month, how long did shipping take, and how many orders arrived each week? SQL can answer those questions directly when date columns are treated as dates.
In SQL for Files, you can practice date queries in the browser using guided order data or your own local files with DuckDB WASM.
Filter date ranges with an exclusive upper bound
For month ranges, a lower bound plus an exclusive upper bound is often safer than BETWEEN, especially when timestamp values enter the picture.
SELECT order_id, order_date
FROM orders
WHERE order_date >= DATE '2024-02-01'
AND order_date < DATE '2024-03-01';Extract parts of a date
EXTRACT pulls out useful pieces like month, year, quarter, or day. This is helpful for grouped reports and quick checks.
SELECT EXTRACT(MONTH FROM order_date) AS order_month, COUNT(*) AS order_count
FROM orders
GROUP BY EXTRACT(MONTH FROM order_date)
ORDER BY order_month;Watch out for month-only grouping
Month number alone mixes January from every year. For real reports, DATE_TRUNC can keep year and month together.
Measure duration with DATE_DIFF
DATE_DIFF measures the distance between two dates. That makes it useful for shipping time, lead time, overdue tasks, retention, and subscription length.
SELECT order_id, DATE_DIFF('day', order_date, ship_date) AS days_to_ship
FROM orders
ORDER BY order_id;Practice the Working with Dates chapter
- Filter February orders with a precise date range.
- Extract month values to build monthly counts.
- Use DATE_DIFF to calculate days between order and shipment.
Continue in the editor
Open SQL for Files to add your own CSV, JSON, or Parquet files and try these examples locally in your browser.
Open editorRelated Learn SQL lessons
Related guides
SQL WHERE Clause Explained: Filtering Rows with AND, OR, and LIKE
Filtering is where SQL starts to feel useful: keep only the rows that answer your question, then combine conditions as your questions get sharper.
SQL DISTINCT, GROUP BY, and HAVING: From Unique Values to Grouped Reports
DISTINCT cleans up repeated values, GROUP BY creates summaries per category, and HAVING filters those summaries after aggregation.
Practical SQL Examples for CSV, JSON, and Parquet Files
A compact collection of SQL patterns you can adapt for local file analysis in SQL for Files.