Careeroza
Date Functions
Working with Dates
Dates are where databases differ the most. The safest format to write literal dates is ISO: 'YYYY-MM-DD'.
| Task | MySQL | SQL Server | PostgreSQL | SQLite |
|---|---|---|---|---|
| Today | CURDATE() | CAST(GETDATE() AS DATE) | CURRENT_DATE | date('now') |
| Now | NOW() | GETDATE() | NOW() | datetime('now') |
| Year of a date | YEAR(d) | YEAR(d) | EXTRACT(YEAR FROM d) | strftime('%Y', d) |
| Add 30 days | DATE_ADD(d, INTERVAL 30 DAY) | DATEADD(day, 30, d) | d + INTERVAL '30 days' | date(d, '+30 days') |
| Days between | DATEDIFF(d2, d1) | DATEDIFF(day, d1, d2) | d2 - d1 | julianday(d2) - julianday(d1) |
| Format | DATE_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
| OrderID | OrderDate | Year | Month |
|---|---|---|---|
| 101 | 2024-01-05 | 2024 | 01 |
| 102 | 2024-01-12 | 2024 | 01 |
| 103 | 2024-02-03 | 2024 | 02 |
| 104 | 2024-02-18 | 2024 | 02 |
| 105 | 2024-03-01 | 2024 | 03 |
| 106 | 2024-03-09 | 2024 | 03 |
| 107 | 2024-03-22 | 2024 | 03 |
| 108 | 2024-04-02 | 2024 | 04 |
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
| OrderID | OrderDate | DueDate |
|---|---|---|
| 101 | 2024-01-05 | 2024-02-04 |
| 102 | 2024-01-12 | 2024-02-11 |
| 103 | 2024-02-03 | 2024-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
| FirstName | HireDate | YearsOfService |
|---|---|---|
| Rahul | 2019-04-01 | 5 |
| Sara | 2021-07-15 | 3 |
| David | 2020-11-02 | 4 |
| Ananya | 2022-01-10 | 2 |
| James | 2018-09-23 | 6 |
| Fatima | 2017-03-05 | 7 |
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
| OrderID | CustomerID | EmployeeID | OrderDate | Amount |
|---|---|---|---|---|
| 101 | 1 | 2 | 2024-01-05 | 245.5 |
| 102 | 4 | 3 | 2024-01-12 | 89.9 |
| 103 | 2 | 2 | 2024-02-03 | 412 |
| 104 | 1 | 3 | 2024-02-18 | 56.25 |
| 105 | 5 | NULL | 2024-03-01 | 150 |
| 106 | 3 | 2 | 2024-03-09 | 320.75 |
| 107 | 4 | 3 | 2024-03-22 | 27 |
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.