Date Range
Filtering in SQL
Learn how to query rows by date ranges and time windows using WHERE clauses, BETWEEN, and date functions.
What Is Date Filtering?
Date filtering means selecting only the rows from a table that fall within a specific time period. Instead of returning every row, you ask the database: "Give me only the records where the date column is inside my chosen window."
Why Date Ranges Matter
Visualizing a Date Range
Core Syntax: BETWEEN
FROM orders
WHERE order_date BETWEEN '2024-03-01'
AND '2024-03-31';
Alternative: Comparison Operators
FROM orders
WHERE order_date >= '2024-03-01'
AND order_date < '2024-04-01';
BETWEEN vs Comparison Operators
| BETWEEN | \(\ge\) / \(<\) | |
|---|---|---|
| Readability | Concise and clean | Slightly longer |
| Inclusivity | Both ends included | You choose per end |
| DATETIME safety | Can miss times | Precise control |
| Best for | DATE columns | DATETIME / TIMESTAMP |
Date Types Quick Reference
Step-by-Step Approach
Example 1: All Orders in Q1
Find every order placed in Q1 2024 (January 1 through March 31). The order_date column is type DATE.
FROM orders
WHERE order_date BETWEEN '2024-01-01'
AND '2024-03-31';
Example 2: Last 7 Days (Dynamic)
Find all logins in the last 7 days. The login_time column is type DATETIME. We use a function to compute "today minus 7 days."
SELECT user_id, login_time
FROM logins
WHERE login_time >= CURDATE() - INTERVAL 7 DAY;
Example 3: The DATETIME Trap
Suppose created_at is a DATETIME. A user created at '2024-03-31 15:30:00': will BETWEEN catch it?
WHERE created_at BETWEEN '2024-03-01'
AND '2024-03-31';
-- '2024-03-31' means '2024-03-31 00:00:00'
-- So 15:30:00 on March 31 is EXCLUDED!
WHERE created_at >= '2024-03-01'
AND created_at < '2024-04-01';
Useful Date Functions
| Function | MySQL | PostgreSQL |
|---|---|---|
| Today's date | CURDATE() | CURRENT_DATE |
| Current moment | NOW() | NOW() |
| Extract year | YEAR(col) | EXTRACT(YEAR FROM col) |
| Add days | col + INTERVAL 7 DAY | col + INTERVAL '7 days' |
| Subtract days | col - INTERVAL 30 DAY | col - INTERVAL '30 days' |
Filtering by Date Parts
Sometimes you need all rows from a specific month or year, regardless of the exact day. Date extraction functions let you do this.
SELECT * FROM orders
WHERE MONTH(order_date) = 3;
-- All orders in 2024
SELECT * FROM orders
WHERE YEAR(order_date) = 2024;
Common Mistakes
Question 1 of 5
Which SQL keyword selects rows where a date column falls within a range, inclusive of both endpoints?
Question 2 of 5
A table has a DATETIME column called created_at. You want all rows from March 2024. Which WHERE clause is safest?
Question 3 of 5
What does CURDATE() - INTERVAL 7 DAY return in MySQL?
Question 4 of 5
Why might wrapping a column in YEAR(order_date) = 2024 be slower than a range comparison on large tables?
Question 5 of 5
Given a DATE column, which query returns all rows from exactly February 2024, including Feb 29 (leap year)?