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.
Writing a date
Section titled “Writing a date”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.
Date types
Section titled “Date types”| 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.
Comparing dates
Section titled “Comparing dates”Dates compare as you would expect: earlier dates are smaller. The invoices issued in March 2025:
SELECT InvoiceID, InvoiceDateFROM InvoicesWHERE 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.
The time-of-day trap
Section titled “The time-of-day trap”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 InvoicesWHERE InvoiceDate = '2025-03-04';Ask for the whole day as a range instead:
SELECT * FROM InvoicesWHERE InvoiceDate >= '2025-03-04' AND InvoiceDate < '2025-03-05';The same trap catches BETWEEN, whose upper end stops at midnight.
Days between two dates
Section titled “Days between two dates”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.
Today’s date
Section titled “Today’s date”| Database | Today |
|---|---|
| PostgreSQL, MySQL, SQLite | CURRENT_DATE |
| SQL Server | CAST(GETDATE() AS date) |
| Oracle | TRUNC(SYSDATE) |