Date Functions in SQL: Extract, Add and Subtract Dates With Examples

9 min read

Date functions in SQL do three jobs: pull a part out of a date (the year, the month, the day of the week), shift a date forward or back (add 2 days, subtract a month), and measure the gap between two dates (days from order to delivery). In MySQL those are MONTH(d), DATE_ADD(d, INTERVAL 2 DAY) and DATEDIFF(later, earlier). Every database has all three, but the function names differ more here than anywhere else in SQL.

That is why this lesson does two things. It works through the common analyst questions on one dataset, written in MySQL, and then gives a single table with the equivalent in MySQL, PostgreSQL, SQL Server and SQLite. If you only need the syntax for your database, skip to that table.

The data used throughout

A Hyderabad diagnostics lab takes test bookings at three branches. Each booking records when it was made, when the sample was collected, and when the report was ready. The lab promises reports within two days of collection. The last two reports are still pending, so reported_on is NULL.

booking_id branch booked_at collected_on reported_on
B01 Gachibowli 2026-09-28 08:15 2026-09-28 2026-09-29
B02 Kukatpally 2026-09-30 19:40 2026-10-01 2026-10-04
B03 Banjara Hills 2026-10-03 07:05 2026-10-03 2026-10-04
B04 Gachibowli 2026-10-17 09:30 2026-10-17 2026-10-21
B05 Kukatpally 2026-10-25 11:00 2026-10-26 2026-10-27
B06 Banjara Hills 2026-10-31 23:50 2026-11-01 2026-11-02
B07 Gachibowli 2026-11-07 06:45 2026-11-07 NULL
B08 Kukatpally 2026-11-08 10:20 2026-11-09 NULL

booked_at is a DATETIME (date and time), while collected_on and reported_on are DATE columns (date only). That difference matters later, in the BETWEEN trap.

The core functions at a glance

These are the functions behind every example below, in MySQL syntax.

Function What it does Syntax Example and result
YEAR, MONTH, DAY Pull out one part as a number MONTH(date) MONTH(‘2026-10-17’) gives 10
DAYNAME, MONTHNAME Pull out a part as a name DAYNAME(date) DAYNAME(‘2026-10-17’) gives Saturday
HOUR Hour from a datetime HOUR(datetime) HOUR(‘2026-10-31 23:50’) gives 23
DATE_ADD Add an interval DATE_ADD(date, INTERVAL n unit) DATE_ADD(‘2026-10-17’, INTERVAL 2 DAY) gives 2026-10-19
DATE_SUB Subtract an interval DATE_SUB(date, INTERVAL n unit) DATE_SUB(‘2026-11-12’, INTERVAL 7 DAY) gives 2026-11-05
DATEDIFF Days between two dates DATEDIFF(later, earlier) DATEDIFF(‘2026-10-21’, ‘2026-10-17’) gives 4
CURDATE, NOW Today’s date, or date and time CURDATE() Returns the server’s current date
DATE_FORMAT Turn a date into text in a chosen layout DATE_FORMAT(date, format) DATE_FORMAT(‘2026-10-17’, ‘%d-%m-%Y’) gives 17-10-2026
LAST_DAY Last day of that month LAST_DAY(date) LAST_DAY(‘2026-10-17’) gives 2026-10-31

Example 1: pull out the month and count bookings per month

The lab’s manager wants bookings per month. The month comes out of a date with DATE_FORMAT(d, ‘%Y-%m’), which keeps the year attached. Grouping by MONTH(d) alone would merge October 2026 with October 2025 as soon as you have more than a year of data.

Part SQL (MySQL)
Month as text SELECT DATE_FORMAT(collected_on, ‘%Y-%m’) AS month, COUNT(*) AS bookings
Source FROM bookings
Group by the same expression GROUP BY DATE_FORMAT(collected_on, ‘%Y-%m’) ORDER BY month
month bookings
2026-09 1
2026-10 4
2026-11 3

Now run the same query on booked_at instead of collected_on, and September has 2 bookings, October 4 and November 2. B02 was booked on 30 September but collected on 1 October; B06 was booked on 31 October and collected on 1 November. Neither answer is wrong. They answer different questions (demand versus lab workload), and a monthly report must say which date it uses. Two teams counting “October bookings” off different date columns is a very common reason dashboards disagree.

The day of the week works the same way. DAYNAME(booked_at) shows that six of the eight bookings were made on a Saturday or Sunday; only B01 (a Monday) and B02 (a Wednesday) fell on weekdays. That kind of finding is what decides weekend staffing.

Example 2: add days to get a due date, and compare

The lab promises a report within two days of collection, so the due date is collected_on plus 2 days. Comparing reported_on with it flags late reports. The gap between two dates, in days, is DATEDIFF.

Part SQL (MySQL)
Columns SELECT booking_id, collected_on,
Add days DATE_ADD(collected_on, INTERVAL 2 DAY) AS due_on, reported_on,
Gap between dates DATEDIFF(reported_on, collected_on) AS tat_days,
Status CASE WHEN reported_on IS NULL THEN ‘Pending’ WHEN reported_on > DATE_ADD(collected_on, INTERVAL 2 DAY) THEN ‘Late’ ELSE ‘On time’ END AS status
Source FROM bookings
booking_id collected_on due_on reported_on tat_days status
B01 2026-09-28 2026-09-30 2026-09-29 1 On time
B02 2026-10-01 2026-10-03 2026-10-04 3 Late
B03 2026-10-03 2026-10-05 2026-10-04 1 On time
B04 2026-10-17 2026-10-19 2026-10-21 4 Late
B05 2026-10-26 2026-10-28 2026-10-27 1 On time
B06 2026-11-01 2026-11-03 2026-11-02 1 On time
B07 2026-11-07 2026-11-09 NULL NULL Pending
B08 2026-11-09 2026-11-11 NULL NULL Pending

TAT, turnaround time, is the standard measure in any lab, hospital or service business. DATEDIFF on a NULL gives NULL, which is right: a report that does not exist has no turnaround. The CASE expression tests for NULL first for exactly that reason; our lesson on CASE WHEN in SQL explains why the order matters.

Averaged by branch, the same expression shows where the delays are:

Part SQL (MySQL)
Averages SELECT branch, COUNT(reported_on) AS reported, ROUND(AVG(DATEDIFF(reported_on, collected_on)), 1) AS avg_tat
Group FROM bookings GROUP BY branch ORDER BY avg_tat DESC
branch reported avg_tat
Gachibowli 2 2.5
Kukatpally 2 2.0
Banjara Hills 2 1.0

Gachibowli averages two and a half days against a two-day promise, pulled up by B04’s four days. AVG skips the pending rows because their DATEDIFF is NULL, which is also why the count uses COUNT(reported_on), not COUNT(*).

Example 3: filter relative to today

Most operational reports are relative: the last 7 days, pending for more than 3 days. CURDATE() returns today’s date, so the filter moves forward on its own every day. The results below are as of 12 November 2026.

Question SQL (MySQL) Result
Samples collected in the last 7 days SELECT booking_id FROM bookings WHERE collected_on >= DATE_SUB(CURDATE(), INTERVAL 7 DAY) B07, B08
How long each pending report has waited SELECT booking_id, DATEDIFF(CURDATE(), collected_on) AS days_waiting FROM bookings WHERE reported_on IS NULL B07 at 5 days, B08 at 3 days

B07 has waited five days against a two-day promise, so it is the one to chase. Note the order of arguments: in MySQL, DATEDIFF puts the later date first. SQL Server reverses it and adds a unit, DATEDIFF(day, earlier, later). Mixing the two up gives negative numbers, which at least are easy to spot.

Example 4: the BETWEEN trap with datetime columns

To get bookings made in October, the obvious query is WHERE booked_at BETWEEN ‘2026-10-01’ AND ‘2026-10-31’. It returns three rows: B03, B04 and B05. B06, booked at 23:50 on 31 October, is missing.

The reason: booked_at holds a time, and ‘2026-10-31’ on its own means midnight at the start of 31 October. Anything later that day is outside the range. The safe pattern is a half-open range, from the first day up to but not including the first day of the next month:

Part SQL
Correct month filter SELECT booking_id, booked_at FROM bookings WHERE booked_at >= ‘2026-10-01’ AND booked_at < ‘2026-11-01’

That returns all four October bookings. It also works the same whether the column is a DATE or a DATETIME, and it lets the database use an index on booked_at. Writing WHERE MONTH(booked_at) = 10 also finds four rows, but wrapping the column in a function stops most databases from using an index, and on a table of a crore rows that is the difference between one second and one minute.

Example 5: first and last day of the month, and adding months

Monthly reports often need the first or last day of a month. In MySQL, LAST_DAY(‘2026-10-17’) gives 2026-10-31, and DATE_FORMAT(‘2026-10-17’, ‘%Y-%m-01’) gives the first day, 2026-10-01. PostgreSQL has DATE_TRUNC(‘month’, d), and SQL Server has EOMONTH(d) for the last day.

Adding a month has an edge case worth knowing. What is 31 January plus one month? MySQL, PostgreSQL and SQL Server all answer 28 February 2026, clamping to the last valid day. SQLite answers 3 March, because it rolls the extra days over. If you are calculating EMI due dates or subscription renewals, test the 29th, 30th and 31st of a month before trusting the result.

Date functions in MySQL, PostgreSQL, SQL Server and SQLite

This is the table to keep open. Each row is one task; d stands for a date or datetime column.

Task MySQL PostgreSQL SQL Server SQLite
Today’s date CURDATE() CURRENT_DATE CAST(GETDATE() AS DATE) date(‘now’)
Current date and time NOW() NOW() GETDATE() datetime(‘now’)
Year YEAR(d) EXTRACT(YEAR FROM d) YEAR(d) strftime(‘%Y’, d)
Month number MONTH(d) EXTRACT(MONTH FROM d) MONTH(d) strftime(‘%m’, d)
Month name MONTHNAME(d) TO_CHAR(d, ‘FMMonth’) DATENAME(month, d) Not built in
Day of week name DAYNAME(d) TO_CHAR(d, ‘FMDay’) DATENAME(weekday, d) Not built in
Day of week number DAYOFWEEK(d), Sunday is 1 EXTRACT(DOW FROM d), Sunday is 0 DATEPART(weekday, d), depends on DATEFIRST setting strftime(‘%w’, d), Sunday is 0
Add 2 days DATE_ADD(d, INTERVAL 2 DAY) d + INTERVAL ‘2 days’ DATEADD(day, 2, d) date(d, ‘+2 days’)
Add 1 month DATE_ADD(d, INTERVAL 1 MONTH) d + INTERVAL ‘1 month’ DATEADD(month, 1, d) date(d, ‘+1 month’), rolls over
Days between DATEDIFF(later, earlier) later – earlier, on DATE columns DATEDIFF(day, earlier, later) julianday(later) – julianday(earlier)
Months between TIMESTAMPDIFF(MONTH, earlier, later) Use AGE(later, earlier) DATEDIFF(month, earlier, later), counts month boundaries Not built in
First day of month DATE_FORMAT(d, ‘%Y-%m-01’) DATE_TRUNC(‘month’, d) DATETRUNC(month, d) from 2022 date(d, ‘start of month’)
Last day of month LAST_DAY(d) DATE_TRUNC(‘month’, d) + INTERVAL ‘1 month – 1 day’ EOMONTH(d) date(d, ‘start of month’, ‘+1 month’, ‘-1 day’)
Show as DD-MM-YYYY DATE_FORMAT(d, ‘%d-%m-%Y’) TO_CHAR(d, ‘DD-MM-YYYY’) FORMAT(d, ‘dd-MM-yyyy’) strftime(‘%d-%m-%Y’, d)
Text to date STR_TO_DATE(’17-10-2026′, ‘%d-%m-%Y’) TO_DATE(’17-10-2026′, ‘DD-MM-YYYY’) CONVERT(date, ’17-10-2026′, 105) Store as YYYY-MM-DD text

Three rows deserve a warning. SQL Server’s DATEDIFF(month, …) counts how many month boundaries are crossed, so 31 October to 1 November is one month, though it is one day. PostgreSQL’s DATE_TRUNC returns a timestamp, so cast it with ::date if you want a plain date. And SQLite has no real date type at all: dates are text, and they only sort and compare correctly in the YYYY-MM-DD format. A smaller one: in PostgreSQL, the FM prefix in ‘FMMonth’ stops TO_CHAR padding the name with trailing spaces.

Mistakes people make with dates

Storing dates as text in DD-MM-YYYY format. ’05-11-2026′ sorts before ’17-10-2026′ as text, so ORDER BY and MAX give the wrong answer. Store dates in a DATE column, and format them for Indian readers only at the end, with DATE_FORMAT or TO_CHAR.

BETWEEN on a datetime column. It drops everything after midnight on the last day, as Example 4 showed. Use greater-than-or-equal and less-than.

Ignoring time zones. Indian Standard Time is UTC plus 5 hours 30 minutes. Many applications store timestamps in UTC. If booked_at were in UTC, B06’s 23:50 on 31 October would be 05:20 on 1 November in Hyderabad, and it would belong to November’s numbers. Check which time zone a column is in before building a daily or monthly report. MySQL has CONVERT_TZ, PostgreSQL has AT TIME ZONE ‘Asia/Kolkata’, and SQL Server has AT TIME ZONE ‘India Standard Time’.

Grouping by MONTH() without the year. Fine for one year of data, wrong the moment a second year arrives.

Wrapping an indexed column in a function in WHERE. YEAR(booked_at) = 2026 cannot use the index on booked_at; a range on the raw column can.

Dates are where joins and aggregates get combined most often in real reporting work: our SQL joins guide covers matching orders to deliveries, and date questions such as “orders in the last 30 days” and “month-on-month growth” come up throughout our SQL interview questions. For choosing the right date and time column type in the first place, see SQL database types. The SQL for data analysis path shows what to learn next.

Frequently asked questions

What are date functions in SQL?

Date functions are built-in SQL functions that work with date and time values. They extract parts of a date such as the year, month or weekday, add or subtract intervals such as days or months, calculate the difference between two dates, and format dates as text. Common ones include YEAR, MONTH, DATE_ADD, DATEDIFF and CURDATE in MySQL, with different names in other databases.

How do I get the month from a date in SQL?

In MySQL and SQL Server use MONTH(date), which returns a number from 1 to 12. In PostgreSQL use EXTRACT(MONTH FROM date), and in SQLite use strftime(‘%m’, date). For monthly reports, extract the year and month together, such as DATE_FORMAT(date, ‘%Y-%m’) in MySQL, so that the same month in different years is not merged.

How do I add days to a date in SQL?

In MySQL use DATE_ADD(date, INTERVAL 7 DAY). In PostgreSQL add an interval, such as date + INTERVAL ‘7 days’, or simply date + 7 on a DATE column. In SQL Server use DATEADD(day, 7, date), and in SQLite use date(date, ‘+7 days’). The same functions add months or years by changing the unit.

How do I calculate the difference between two dates in SQL?

In MySQL, DATEDIFF(later, earlier) returns the number of days. SQL Server uses DATEDIFF(day, earlier, later), with the unit first and the dates in the opposite order. In PostgreSQL, subtracting one DATE from another gives the number of days directly. For months or years, use TIMESTAMPDIFF in MySQL or AGE in PostgreSQL.

How do I get today’s date in SQL?

Use CURDATE() or CURRENT_DATE in MySQL, CURRENT_DATE in PostgreSQL, CAST(GETDATE() AS DATE) in SQL Server, and date(‘now’) in SQLite. For the current date and time together, use NOW() in MySQL and PostgreSQL or GETDATE() in SQL Server. These return the database server’s time, which may be in UTC rather than Indian time.

How do I filter records for the last 30 days in SQL?

Compare the date column with today’s date minus 30 days, for example WHERE order_date >= DATE_SUB(CURDATE(), INTERVAL 30 DAY) in MySQL, or WHERE order_date >= CURRENT_DATE – INTERVAL ’30 days’ in PostgreSQL. In SQL Server, use WHERE order_date >= DATEADD(day, -30, CAST(GETDATE() AS DATE)). Keep the column itself unwrapped so the database can use its index.

Get dates right before they reach a dashboard

Nearly every business report is cut by date, and most of the quiet errors in those reports come from the wrong date column, a BETWEEN that drops the last day, or a time zone nobody checked.

SkilloVilla’s SQL: Beginner to Advanced course covers the fundamental statements, conditional functions, aggregation, joins and advanced SQL statements, taught in live classes with mentor support and practice on SQL playgrounds. If you want SQL as part of a full analyst programme with Excel, Python, Power BI and placement support, see the Data Analytics with Python track.

Statistics for Data Analytics: The Topics an Analyst Needs,…

Statistics for data analytics: the topics an analyst uses, grouped into a learning path, with the business question each answers and a study plan.
SkilloVilla Team
6 min read

Standard Deviation and Variance for Data Analysts, With Worked…

Standard deviation and variance for data analysts: population vs sample (n vs n-1), a worked calculation, Excel and SQL functions, and what it means.
SkilloVilla Team
7 min read

Power BI vs Tableau: Which to Learn for an…

Power BI vs Tableau compared for Indian job-seekers: job demand, cost, learning curve, data prep, Mac support and sharing, with a side-by-side table.
SkilloVilla Team
5 min read

Leave a Reply