SQL Cookbook Lesson
How to compare two dates in the WHERE clause with SQL
Learn how to compare two dates in the WHERE clause with SQL with examples and explanations from SQLPad.
Problem
You have two dates in your database and you need to compare them in the WHERE clause of your SQL query. You want to understand how to perform this task in both MySQL and PostgreSQL.
Sample Data
Consider the following sample data in a table called Orders:
| OrderID | Product | OrderDate |
|---|---|---|
| 1 | Apple | 2022-01-01 |
| 2 | Banana | 2022-02-01 |
| 3 | Cherry | 2022-03-01 |
We will compare the OrderDate with a specific date to filter the results.
MySQL Solution
SELECT * FROM Orders
WHERE OrderDate > '2022-01-15';
PostgreSQL Solution
SELECT * FROM Orders
WHERE OrderDate > '2022-01-15';
Explanation
In both MySQL and PostgreSQL, date comparison in the WHERE clause is straightforward. You simply need to use comparison operators (like <, >, <=, >=, <>, =) to compare your date field with the date you have.
In the provided solutions, we are selecting all records from the Orders table where the OrderDate is later than January 15, 2022. The date format used in the query should match the date format of your data in the SQL table.
It's important to note that this will compare the full date (year, month, day). If you want to compare only parts of the date, you would need to use database-specific functions to extract the part you are interested in (like YEAR(), MONTH(), DAY() in MySQL or EXTRACT() in PostgreSQL).