Skip to content

SQL Working With Dates

Dates are simple until a time of day sneaks in. This page covers the types that hold them, the safe way to write them, and how to compare and subtract them.

The examples use the Invoices table from the example database.

Write dates as 'YYYY-MM-DD', as in '2025-03-04' for 4 March 2025. Every major database reads this form the same way, whereas '04/03/2025' means 4 March in the UK and 3 April in the US, and different databases guess differently.

Holds PostgreSQL MySQL SQL Server Oracle
a date date DATE date DATE, which also holds a time
a date and time timestamp DATETIME datetime2 TIMESTAMP
a date and time with time zone timestamptz datetimeoffset TIMESTAMP WITH TIME ZONE

SQLite has no date type; it stores dates as text, such as '2025-03-04', and provides functions for working with them.

Choose a plain date type when the time of day does not matter, as for an invoice date. It avoids the trap described below.

Dates compare as you would expect: earlier dates are smaller. The invoices issued in March 2025:

SELECT InvoiceID, InvoiceDate
FROM Invoices
WHERE InvoiceDate >= '2025-03-01' AND InvoiceDate < '2025-04-01'
ORDER BY InvoiceDate;
InvoiceID InvoiceDate
1001 2025-03-04
1002 2025-03-06
1003 2025-03-11
1004 2025-03-12

Writing the range as “on or after the first of the month, and before the first of the next” works whatever the month’s length, and whether or not times are stored.

If a column holds times as well as dates, a value such as 2025-03-04 14:30:00 is not equal to '2025-03-04', which means midnight at the start of that day. So this finds nothing for invoices entered during the day:

SELECT * FROM Invoices
WHERE InvoiceDate = '2025-03-04';

Ask for the whole day as a range instead:

SELECT * FROM Invoices
WHERE InvoiceDate >= '2025-03-04' AND InvoiceDate < '2025-03-05';

The same trap catches BETWEEN, whose upper end stops at midnight.

How long each paid invoice took to pay:

InvoiceID InvoiceDate PaidDate DaysToPay
1001 2025-03-04 2025-04-01 28
1002 2025-03-06 2025-03-28 22

Each database writes the calculation differently:

Database DaysToPay
PostgreSQL PaidDate - InvoiceDate
MySQL DATEDIFF(PaidDate, InvoiceDate)
SQL Server DATEDIFF(day, InvoiceDate, PaidDate)
Oracle PaidDate - InvoiceDate
SQLite julianday(PaidDate) - julianday(InvoiceDate)

Note that MySQL and SQL Server take the two dates in opposite orders.

Database Today
PostgreSQL, MySQL, SQLite CURRENT_DATE
SQL Server CAST(GETDATE() AS date)
Oracle TRUNC(SYSDATE)