Reading history

SQL Date and Time Functions with Examples

5 min read 0 views

Work with dates in SQL: ISO format, extracting year and month, adding days and months, days between dates, grouping by month, and equivalents in MySQL, PostgreSQL and SQL Server.

Almost every real database stores dates: when an order was placed, when a user signed up, when a payment is due. Reports then ask questions such as “sales per month” or “orders in the last 30 days”. This lesson shows how to store dates so they sort and compare correctly, how to pull out the year or month, how to add and subtract time, and how to group rows by period. The examples run on SQLite, and a table at the end maps each function to MySQL, PostgreSQL and SQL Server.

In this lesson you will learn

  • Why dates should be stored in ISO format (YYYY-MM-DD)
  • Extracting parts of a date with strftime
  • Adding and subtracting days and months
  • Counting the days between two dates
  • Grouping and filtering rows by date range

The examples use a small orders table with columns id, customer, order_date, amount and status, holding eight orders from January to March 2026.

Extracting Parts and Doing Date Arithmetic

-- SQLite stores dates as ISO text: YYYY-MM-DD
SELECT id, order_date,
       strftime('%Y', order_date) AS year,
       strftime('%m', order_date) AS month,
       strftime('%w', order_date) AS weekday_0_sun
FROM orders
WHERE id <= 3;

SELECT date('2026-01-31', '+1 month') AS plus_one_month,
       date('2026-03-01', '-1 day') AS day_before,
       julianday('2026-03-30') - julianday('2026-01-05') AS days_between;

Output

+----+------------+------+-------+---------------+
| id | order_date | year | month | weekday_0_sun |
+----+------------+------+-------+---------------+
| 1  | 2026-01-05 | 2026 | 01    | 1             |
| 2  | 2026-01-18 | 2026 | 01    | 0             |
| 3  | 2026-02-02 | 2026 | 02    | 1             |
+----+------------+------+-------+---------------+
(3 rows)

+----------------+------------+--------------+
| plus_one_month | day_before | days_between |
+----------------+------------+--------------+
| 2026-03-03     | 2026-02-28 | 84.0         |
+----------------+------------+--------------+
(1 row)
  • SQLite has no separate date type; dates are stored as text in the form YYYY-MM-DD. Other databases have DATE, TIME and TIMESTAMP types, but the ISO format is still the safest way to write date literals.
  • strftime(format, date) formats a date: %Y is the year, %m the month, %d the day and %w the weekday (0 is Sunday).
  • date(value, modifier) shifts a date. Note that 31 January plus one month gives 3 March in SQLite, because “31 February” rolls over. Month arithmetic near the end of a month needs care in every database.
  • julianday() turns a date into a day number, so subtracting two of them gives the days between: 84 here.

Grouping and Filtering by Date

-- Monthly totals of delivered orders
SELECT strftime('%Y-%m', order_date) AS month,
       COUNT(*) AS orders,
       SUM(amount) AS total
FROM orders
WHERE status = 'delivered'
GROUP BY month
ORDER BY month;

-- Orders in a date range (ISO text compares correctly)
SELECT id, customer, order_date
FROM orders
WHERE order_date BETWEEN '2026-02-01' AND '2026-02-28';

Output

+---------+--------+-------+
| month   | orders | total |
+---------+--------+-------+
| 2026-01 | 2      | 1650  |
| 2026-02 | 1      | 2300  |
| 2026-03 | 2      | 1800  |
+---------+--------+-------+
(3 rows)

+----+----------+------------+
| id | customer | order_date |
+----+----------+------------+
| 3  | Karim    | 2026-02-02 |
| 4  | Joya     | 2026-02-14 |
| 5  | Rina     | 2026-02-27 |
+----+----------+------------+
(3 rows)
  • strftime('%Y-%m', order_date) reduces every date to its month, so GROUP BY can total each month.
  • Because ISO dates sort the same way as text, BETWEEN '2026-02-01' AND '2026-02-28' works correctly. A format like 14/02/2026 would not.
  • If a column holds date and time, BETWEEN ... AND '2026-02-28' misses times later on the 28th. The safer pattern is order_date >= '2026-02-01' AND order_date < '2026-03-01'.
  • For “today”, SQLite uses date('now'), so the last 30 days is WHERE order_date >= date('now', '-30 days').

Same Task, Different Databases

TaskSQLiteMySQLPostgreSQLSQL Server
Todaydate('now')CURDATE()CURRENT_DATECAST(GETDATE() AS date)
Year of dstrftime('%Y', d)YEAR(d)EXTRACT(YEAR FROM d)YEAR(d)
d + 7 daysdate(d, '+7 days')DATE_ADD(d, INTERVAL 7 DAY)d + INTERVAL '7 days'DATEADD(day, 7, d)
Days betweenjulianday(b) - julianday(a)DATEDIFF(b, a)b - aDATEDIFF(day, a, b)

Common Mistakes

  1. Storing dates as DD/MM/YYYY text, which breaks sorting and comparison.
  2. Using BETWEEN with timestamps and losing rows on the last day.
  3. Ignoring time zones: store times in UTC and convert when displaying.
  4. Wrapping the column in a function inside WHERE (for example WHERE strftime('%Y', order_date) = '2026'), which prevents index use; a range condition is faster.

Practice Exercises

Exercise 1. List orders placed on a Saturday or Sunday.

Show answer
SELECT id, order_date
FROM orders
WHERE strftime('%w', order_date) IN ('0', '6');

It returns orders 2, 4 and 7.

Exercise 2. Show each order with a “due date” 14 days after the order date.

Show answer
SELECT id, order_date, date(order_date, '+14 days') AS due_date
FROM orders;

Frequently Asked Questions

What is the difference between DATE, DATETIME and TIMESTAMP?

DATE holds only a calendar day. DATETIME and TIMESTAMP also hold a time of day. In MySQL, TIMESTAMP values are converted to and from UTC, while DATETIME values are stored as written.

Why use ISO 8601 format?

YYYY-MM-DD is unambiguous in every country, sorts correctly as text and is accepted as a literal by all major databases.

Summary

  • Store dates as ISO YYYY-MM-DD (or a proper date type).
  • Extract parts with strftime (SQLite) or EXTRACT/YEAR() elsewhere.
  • Shift dates with modifiers or INTERVAL, and check month-end behaviour.
  • Filter with half-open ranges: >= start AND < next_start.

Next: SQL UNION, INTERSECT and EXCEPT.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *