Course contentsShow
← Data Science
Lesson 863 of 2,14522. SQL FoundationsFree lesson

Filtering Dates and Timestamps

Apply WHERE conditions to date columns using proper date formats and comparison operators.

Filtering Dates and Timestamps

You'll learn how to write WHERE conditions that filter rows based on date and timestamp columns using the right formats and comparison operators.

The Core Idea

Dates and timestamps are stored in databases using special data types (like DATE, DATETIME, or TIMESTAMP), not as plain text. To filter them effectively, you need to write your conditions using the correct date format and comparison operators—just like you did with numbers and text in earlier lessons.

Think of dates as points on a timeline. When you filter by date, you're essentially asking: "Show me only the rows that fall before, after, or on this specific point in time."

Writing Date Filters

Most databases expect dates in the format 'YYYY-MM-DD' (year-month-day), like '2024-03-15'. You can use all the comparison operators you already know:

SELECT * 
FROM orders
WHERE order_date = '2024-03-15'

This returns orders placed exactly on March 15, 2024.

SELECT * 
FROM orders
WHERE order_date >= '2024-01-01'

This returns all orders from January 1, 2024, onward.

You can combine operators with BETWEEN too:

SELECT * 
FROM sales
WHERE sale_date BETWEEN '2024-01-01' AND '2024-03-31'

This retrieves all sales from the first quarter of 2024.

Timestamps Include Time

Timestamps store both date and time (e.g., '2024-03-15 14:30:00'). When filtering, be mindful: order_timestamp = '2024-03-15' might not match records that have a specific time component.

Key Takeaway: Filter date columns by writing conditions with properly formatted date strings ('YYYY-MM-DD') and comparison operators—dates behave like numbers on a timeline, making <, >, =, and BETWEEN your filtering tools.