How To Compare Dates In Sql

5 min read

Comparing dates in SQL is a fundamental skill for anyone working with relational databases, yet it remains a common source of bugs and performance bottlenecks. Whether you are filtering transaction logs, generating monthly reports, or scheduling automated jobs, understanding how your specific database engine handles temporal data types is critical. This guide explores the standard syntax, engine-specific nuances, common pitfalls like time components and time zones, and optimization strategies to ensure your date comparisons are both accurate and efficient.

Understanding SQL Date and Time Data Types

Before writing comparison logic, you must identify the data type of the column you are querying. The three most common types behave differently during comparisons:

  • DATE: Stores only the calendar date (Year, Month, Day). Example: 2023-10-25. Comparisons are straightforward because no time component exists.
  • DATETIME / TIMESTAMP: Stores both date and time, often down to fractions of a second. Example: 2023-10-25 14:30:00.123. This is where most comparison errors occur.
  • TIMESTAMPTZ / DATETIMEOFFSET: Stores date, time, and time zone offset (or UTC equivalent). Essential for global applications.

Key Distinction: A DATE value represents the entire 24-hour period. A DATETIME value represents a specific instant. Comparing a DATETIME column to a DATE literal (e.g., '2023-10-25') usually implies a time of 00:00:00 (midnight), potentially excluding data from the rest of that day Less friction, more output..

Basic Comparison Operators

Standard SQL supports the usual comparison operators for temporal types. These work consistently across PostgreSQL, MySQL, SQL Server, Oracle, and SQLite Simple as that..

Operator Description
= Equal to (exact match for the instant). Still, =`
> Greater than (later than).
>= Greater than or equal to.
<> or `!On top of that,
< Less than (earlier than).
<= Less than or equal to.

Example: Finding orders placed exactly at a specific second.

SELECT order_id, customer_id, created_at
FROM orders
WHERE created_at = '2023-10-25 14:30:00';

The "Midnight Trap": Comparing Datetimes to Dates

The most frequent error developers make is filtering a DATETIME column using a DATE string literal It's one of those things that adds up..

The Problem:

-- DANGEROUS: Misses almost the entire day
SELECT * FROM events
WHERE event_timestamp = '2023-10-25';

In most engines, '2023-10-25' is implicitly cast to '2023-10-25 00:00:00.000'. This query only returns rows occurring exactly at midnight Worth knowing..

Correct Pattern: Half-Open Intervals (Best Practice)

The industry-standard, SARGable (Search ARGument Able) method for "getting all rows for a specific day" uses a half-open interval: >= start AND < next_day_start Practical, not theoretical..

-- SAFE & PERFORMANT: Catches the full 24 hours
SELECT * FROM events
WHERE event_timestamp >= '2023-10-25'
  AND event_timestamp < '2023-10-26';

Why this wins:

  1. Accuracy: Captures 2023-10-25 23:59:59.999.
  2. Index Usage: The optimizer can perform an Index Range Scan (Seek) because the column event_timestamp is not wrapped in a function.
  3. Type Agnostic: Works identically whether the column is DATE, DATETIME, TIMESTAMP, or TIMESTAMPTZ.

Using BETWEEN — Proceed with Caution

BETWEEN is inclusive on both ends (WHERE x BETWEEN a AND b translates to x >= a AND x <= b).

The Risk with Datetimes:

-- RISKY for DATETIME precision
WHERE event_timestamp BETWEEN '2023-10-25' AND '2023-10-25 23:59:59.999'

You must know the maximum precision of your data type (milliseconds? microseconds? nanoseconds?) to define the upper bound correctly. If the column stores microseconds but you filter to milliseconds, you lose data.

Verdict: Avoid BETWEEN for high-precision DATETIME ranges. Stick to the half-open interval pattern (>= AND <) That's the part that actually makes a difference..

Engine-Specific Syntax and Functions

While the logic remains the same, syntax for generating dates (like "yesterday" or "start of month") varies significantly.

1. Relative Anchors (e.g., "Last 30 Days")

Never hardcode dates in production code. Always anchor to the current time or a maximum date in the table Simple, but easy to overlook..

Database "Last 30 Days" Syntax
PostgreSQL WHERE created_at >= CURRENT_DATE - INTERVAL '30 days'
MySQL WHERE created_at >= DATE_SUB(NOW(), INTERVAL 30 DAY)
SQL Server WHERE created_at >= DATEADD(DAY, -30, GETDATE())
Oracle WHERE created_at >= SYSDATE - 30 (implicit day math)
SQLite WHERE created_at >= date('now', '-30 days')

Pro Tip: For reporting consistency, anchor to CURRENT_DATE (midnight today) rather than NOW()/GETDATE() (current instant), unless you need real-time precision. This prevents the "moving window" effect where a report run at 11:59 PM returns different data than one run at 12:01 AM.

2. Truncating to Day/Month/Year (Grouping)

When grouping by day, you must strip the time component.

Database Truncate to Date Syntax
PostgreSQL DATE_TRUNC('day', created_at) or created_at::date
MySQL DATE(created_at)
SQL Server CAST(created_at AS DATE) or CONVERT(DATE, created_at)
Oracle TRUNC(created_at)
SQLite date(created_at)

Performance Warning: Applying a function to the column side (WHERE DATE(created_at) = '2023-10-25') destroys index usage (Full Table Scan). Always apply math to the literal side (the half-open interval method) for filtering. Reserve truncation functions for GROUP BY or SELECT clauses.

Handling Time Zones: The Silent Data Corruptor

If your application serves users across time zones, TIMESTAMP WITHOUT TIME ZONE is a liability. A timestamp 2023-10-25 14:00:00 means different physical instants in New York vs. London.

Best Practice: Store in UTC, Compare

Hot and New

New This Week

Try These Next

Readers Loved These Too

Thank you for reading about How To Compare Dates In Sql. We hope the information has been useful. Feel free to contact us if you have any questions. See you next time — don't forget to bookmark!
⌂ Back to Home