Date Functions

Working with Dates

Dates are where databases differ the most. The safest format to write literal dates is ISO: 'YYYY-MM-DD'.

TaskMySQLSQL ServerPostgreSQLSQLite
TodayCURDATE()CAST(GETDATE() AS DATE)CURRENT_DATEdate('now')
NowNOW()GETDATE()NOW()datetime('now')
Year of a dateYEAR(d)YEAR(d)EXTRACT(YEAR FROM d)strftime('%Y', d)
Add 30 daysDATE_ADD(d, INTERVAL 30 DAY)DATEADD(day, 30, d)d + INTERVAL '30 days'date(d, '+30 days')
Days betweenDATEDIFF(d2, d1)DATEDIFF(day, d1, d2)d2 - d1julianday(d2) - julianday(d1)
FormatDATE_FORMAT(d, '%d/%m/%Y')FORMAT(d, 'dd/MM/yyyy')TO_CHAR(d, 'DD/MM/YYYY')strftime('%d/%m/%Y', d)

Extract Parts of a Date

Example

Year and month of each order (SQLite syntax):

SELECT OrderID, OrderDate,
       strftime('%Y', OrderDate) AS Year,
       strftime('%m', OrderDate) AS Month
FROM Orders;

Result: 8 rows

OrderIDOrderDateYearMonth
1012024-01-05202401
1022024-01-12202401
1032024-02-03202402
1042024-02-18202402
1052024-03-01202403
1062024-03-09202403
1072024-03-22202403
1082024-04-02202404

Date Arithmetic

Example

Due date 30 days after the order, and how long each employee has worked here as of 2024-12-31:

SELECT OrderID, OrderDate, date(OrderDate, '+30 days') AS DueDate
FROM Orders
LIMIT 3;

Result: 3 rows

OrderIDOrderDateDueDate
1012024-01-052024-02-04
1022024-01-122024-02-11
1032024-02-032024-03-04

Example (years of service)

Whole years each employee has worked, as of 2024-12-31:

SELECT FirstName, HireDate,
       CAST((julianday('2024-12-31') - julianday(HireDate)) / 365.25 AS INTEGER) AS YearsOfService
FROM Employees;

Result: 6 rows

FirstNameHireDateYearsOfService
Rahul2019-04-015
Sara2021-07-153
David2020-11-024
Ananya2022-01-102
James2018-09-236
Fatima2017-03-057

Filtering by Date

Example

Orders in Q1 2024. Comparing ISO strings works because they sort correctly:

SELECT * FROM Orders
WHERE OrderDate >= '2024-01-01' AND OrderDate < '2024-04-01';

Result: 7 rows

OrderIDCustomerIDEmployeeIDOrderDateAmount
101122024-01-05245.5
102432024-01-1289.9
103222024-02-03412
104132024-02-1856.25
1055NULL2024-03-01150
106322024-03-09320.75
107432024-03-2227

Tip: Avoid wrapping the column in a function in WHERE (e.g. YEAR(OrderDate) = 2024). It stops the database from using an index on OrderDate; a range comparison can use it.