MySQL
ORACLE
POSTGRESQL
SQL
SQL SERVER

How to Compare Datetimes in SQL: Multiple Approaches

intro

Discover how to compare date and datetime values using SQL operators across MySQL, PostgreSQL, SQL Server, and Oracle.

Compare date, datetime, and time values in an SQL query is a common requirement.

For example, you may want to find all records after a certain date or determine if one timestamp is greater than another. Thanks to the many SQL datetime comparison operator available, that’s an easy task!

Compare Datetimes in SQL With Standard Comparison Operators

In SQL, you can compare date or datetime values using the standard comparison operators (=, <, >, <=, >=) just like numbers. That is possible as long as the values are of a valid date, datetime, or time data types.

That is possible because all major SQL databases support direct datetime comparison. For example, to get rows where an event’s timestamp is after Jan 1, 2025:

Copy
        
1 SELECT * 2 FROM events 3 WHERE event_timestamp >= '2025-01-01';

In the above query, we compare a datetime column (event_timestamp) to a string literal '2025-01-01'. SQL will interpret the string as a date (in ANSI or the default format) and perform the comparison.

In practice, '2025-01-01' is treated as 2025-01-01 00:00:00 (midnight at the start of the day). Thus, any event_timestamp on Jan 1, 2025 at exactly midnight or later will match. If you want strictly after that date (excluding the whole day of Jan 1), you could use > and '2025-01-01 23:59:59' or better, '2025-01-02' as the cutoff.

Notes:

All standard comparison operators work for datetime values. One thing to note is how different database systems treat string literals as dates:

  • In MySQL and PostgreSQL, a string in the format 'YYYY-MM-DD' will be implicitly converted to a date or datetime if compared with a date column. It’s usually safe to use ISO-8601 format ('YYYY-MM-DD' or 'YYYY-MM-DD hh:mi:ss') for date/time literals, as this format is unambiguous.
  • In SQL Server, a bare date string in ISO format is also recognized (assuming ANSI settings). SQL Server might interpret '2025-01-01' as YYYY-MM-DD. For safety, you can use the DATE literal notation or parameterized queries. Learn more about the SQL Server date format.
  • In Oracle, you should either use the DATE literal syntax (e.g., DATE '2025-01-01') or use TO_DATE('2025-01-01','YYYY-MM-DD') to explicitly convert a string to a date. Oracle will not automatically parse a string to date in a comparison without a conversion (unless you rely on NLS date format settings).

How Date, Datetime, and Time Comparisons Work

When comparing dates or timestamps, SQL uses chronological ordering. In particular, an earlier date/time is considered “less than” a later date/time.

For example, '2025-01-01' < '2025-01-02' will yield true, because January 1, 2025 is before January 2, 2025. This works consistently in all SQL databases. You can compare a date/datetime column to a literal as shown, or compare two date columns to each other:

Copy
        
1 -- Find orders where payment date is after order date (i.e., paid late) 2 SELECT * 3 FROM orders 4 WHERE payment_date > order_date;

This will return rows where payment_date is chronologically later than order_date. Similarly, you can check equality or inequality of dates/times:

Copy
        
1 -- Find events that started and ended on the same date 2 SELECT * 3 FROM events 4 WHERE DATE(start_time) = DATE(end_time);

(Assuming start_time and end_time are datetimes, here we cast or extract the date portion to compare just the date.)

Time Component Consideration

If your datetime values include a time portion, be careful when comparing to a date literal. As mentioned, '2025-01-01' is essentially midnight of that day.

Any datetime on the same day but later than 00:00:00 will be considered greater than '2025-01-01'. For example, '2025-01-01 10:45:00' > '2025-01-01' is true, because the first includes a time 10:45am which is later on the same day. Conversely, if you do event_timestamp = '2025-01-01', this will only match rows exactly at midnight on Jan 1, 2025.

Thus, it’s often better to use a range for date-only comparisons:

Copy
        
1 SELECT * FROM events 2 WHERE event_timestamp >= '2025-01-01' 3 AND event_timestamp < '2025-01-02';

This way, you capture the entire day of Jan 1st. In this scenario, consider also using the SQL BETWEEN operator.

If you need to ignore the time part altogether, you can cast the datetime to a date (which truncates the time). For example, in Postgres ::date cast or the DATE() function (MySQL) can extract the date. Then you can compare dates to dates:

Copy
        
1 -- Find events that occurred on the same calendar date 2 SELECT * FROM events 3 WHERE DATE(start_time) = DATE(end_time);

Keep in mind using functions on columns can prevent indexes from being used, so for large data sets a range comparison as shown earlier is preferred for performance.

Tips and Edge Cases

  • Timezone: If your datetimes include time zones (e.g., SQL Server datetimeoffset, Postgres timestamptz), comparisons still work the same—the values are compared in absolute time. Just be mindful if you’re comparing a timestamp without timezone to one with timezone; usually you should convert them to the same type or adjust to the same zone.
  • NULL datetimes: A NULL datetime compared to any value is neither true nor false. Thus, it will be filtered out unless you explicitly check for IS NULL.
  • Comparing across types: If you have a varchar column storing dates (not recommended), you must convert it to date type to compare correctly. Otherwise, it will do a lexicographical string comparison which may give incorrect ordering (e.g., '2/1/2025' as string might not sort correctly). Use your DB’s convert function (e.g., STR_TO_DATE in MySQL, TO_DATE in Oracle) to convert strings to date for comparison.

Conclusion

In summary, comparing datetimes in SQL is straightforward: use < or > for before/after, = for equality (same moment in time), and consider the date vs datetime nuances. All SQL databases allow direct date comparisons, so you can confidently use these operators. Just ensure your values are in date/datetime format and be mindful of the time portion when doing equality or range checks.

(If you need to compute the difference between two datetime values, look into functions like DATEDIFF (SQL Server, MySQL) or date arithmetic functions (PostgreSQL, Oracle)—since the question is about comparing, we focused on <, > and similar comparisons.)

Dbvis download link img
About the author
TheTable
TheTable

The Table by DbVisualizer is where we gather together to learn about and simplify the complexity of working with database technologies.

The Table Icon
Sign up to receive The Table's roundup
More from the table
Title Author Tags Length Published
title

SQL Server CHARINDEX Function (Find Substring Position)

author TheTable tags SQL SERVER 6 min 2025-06-11
title

pg_dumpall: How to Dump All Your PostgreSQL Databases

author Antonello Zanini tags POSTGRESQL 7 min 2025-06-10
title

Database Security: The Most Common Mistakes to Avoid

author Lukas Vileikis tags MARIADB MySQL SECURITY SQL 6 min 2025-06-09
title

The Complete Guide to CONCAT in SQL Queries: Syntax, Examples, and Best Practices

author Leslie S. Gyamfi tags MySQL ORACLE POSTGRESQL SQL SQL SERVER 7 min 2025-06-03
title

How Often Should SQL Transaction Logs Be Backed Up?

author Antonello Zanini tags MySQL POSTGRESQL SQL SQL SERVER 7 min 2025-06-02
title

How to Fix Oracle ORA-00933 Error: SQL Command Not Properly Ended

author TheTable tags ORACLE 4 min 2025-05-28
title

What Is a Database Catalog?

author Antonello Zanini tags MySQL ORACLE POSTGRESQL SQL SQL SERVER 6 min 2025-05-27
title

The Most Common MySQL Error Codes (and How to Avoid Them)

author Lukas Vileikis tags MARIADB MySQL SQL 5 min 2025-05-26
title

Top SQL Performance Tuning Interview Questions and Answers

author TheTable tags SQL 13 min 2025-05-21
title

SQL Server Temp Table Mechanism: Complete Guide

author Antonello Zanini tags SQL SERVER 9 min 2025-05-20

The content provided on dbvis.com/thetable, including but not limited to code and examples, is intended for educational and informational purposes only. We do not make any warranties or representations of any kind. Read more here.