AD JB Toolbox 01 EN

MariaDB Tutorial / Calculate Date Intervals, Differences, and Display Formats

DATE_ADD adds an interval, DATEDIFF and TIMESTAMPDIFF calculate different kinds of differences, and DATE_FORMAT produces display text. Distinguish calendar-day differences from elapsed units, and use a start-inclusive, next-boundary-exclusive range when selecting a complete period.

Define the unit and meaning before choosing a function

A one-month expiry, the count of calendar boundaries crossed and the number of complete elapsed hours are different questions. Use date types for calculations instead of round-tripping through locale-dependent display strings. Verify stored types and time zones using Store Dates and Times with DATE, DATETIME, and TIMESTAMP; Build and Reconcile Monthly Sales, Customer Totals, and Unsold Products applies matching month boundaries to a sales report.

Function Purpose Argument rule
DATE_ADD Add an interval For example, INTERVAL 1 MONTH
DATEDIFF Difference between date portions First date minus second date
TIMESTAMPDIFF Integer difference in a chosen unit Second time value minus first time value
DATE_FORMAT Produce a display string For example, %Y-%m

Check the MariaDB documentation for the syntax and conditions used here: date_add, date_format, datediff.

Compare fixed inputs in the same connection

Select shopcourse and inspect SELECT VERSION(), DATABASE(), @@SESSION.time_zone;. Fixed dates make expected results independent of the day the example is run. The DATE, DATETIME and TIMESTAMP guide explains storage and time-zone conversion; write date literals in unambiguous year-month-day order.

SELECT DATE_ADD('2026-01-31',INTERVAL 1 MONTH);
SELECT DATE_ADD('2026-01-31',INTERVAL 30 DAY);

One month after January 31 is 2026-02-28, while thirty days later is 2026-03-02. A calendar month is not always thirty days. When the target month lacks the original day number, the calculation adjusts to its last valid day. Verify that this matches a subscription’s intended month-end policy.

Compare argument order and ignored time components

SELECT DATEDIFF('2026-02-02 01:00:00','2026-02-01 23:00:00'),
 TIMESTAMPDIFF(HOUR,'2026-02-01 23:00:00','2026-02-02 01:00:00');

The results are one calendar day and two complete hours. DATEDIFF ignores the time portions and subtracts the second date from the first. TIMESTAMPDIFF takes the unit first, then the starting value and ending value. Copying argument order mechanically between the functions can reverse the sign.

An integer-unit difference may omit remaining minutes or seconds. For time-zone or daylight-saving-sensitive durations, define whether stored values are local wall-clock fields or normalized instants. Two DATETIME values do not automatically encode every region’s actual elapsed time.

Use DATE_FORMAT for output rather than storage changes

SELECT DATE_FORMAT('2026-02-05 12:34:56','%Y-%m'),
 DATE_FORMAT('2026-02-05 12:34:56','%Y-%m-%d %H:%i:%s');

The output strings are 2026-02 and 2026-02-05 12:34:56. The minute token is %i; %m denotes the month. Formatting leaves the stored date unchanged and returns a string for display. Formats containing localized month names can depend on session language settings.

Select the entire month with an exclusive upper boundary

Check that dates_21_lab does not already exist, then run this complete setup and query in shopcourse. It does not depend on earlier product tables.

CREATE TABLE dates_21_lab (event_id INT PRIMARY KEY, occurred_at DATETIME NOT NULL)
 ENGINE=InnoDB;
INSERT INTO dates_21_lab VALUES
 (1,'2026-02-01 00:00:00'),(2,'2026-02-28 23:59:59'),(3,'2026-03-01 00:00:00');
SELECT event_id FROM dates_21_lab
WHERE occurred_at >= '2026-02-01' AND occurred_at < '2026-03-01'
ORDER BY event_id;

IDs 1 and 2 qualify; ID 3 at exactly March 1 midnight does not. A boundary at the next month’s start remains clear when fractional-second precision changes, whereas hard-coding the previous day’s final second can miss finer timestamps. Direct range comparisons also make the intended access condition explicit when considering indexes.

Check invalid dates and repeat the small example

For NULL results or warnings, inspect the format, month end, leap-year rules and SQL mode. Do not silently treat incomplete or zero dates as valid business dates because conversion happened to accept them. Decide what missing input means before substituting the current date.

Inspect the table and preserve anything needed before removing only this exercise’s dates_21_lab. DROP TABLE cannot be reversed with an ordinary ROLLBACK.

DROP TABLE shopcourse.dates_21_lab;
More in This Category
MariaDB Tutorial / Calculate Date Intervals, Differences, and Display Formats

MariaDB Tutorial / Calculate Date Intervals, Differences, and Display Formats

Compare calendar months, day differences and complete-hour differences with fixed MariaDB examples. Format dates correctly and select full months using explicit interval boundaries.

MariaDB Tutorial / Build, Secure, Back Up, and Verify an Order Database

MariaDB Tutorial / Build, Secure, Back Up, and Verify an Order Database

Complete an order-database workflow using constrained tables, a limited app account and a checked stock transaction. Define and compare committed-state backup and restoration criteria, including denied operations.

MariaDB Tutorial / Read EXPLAIN and Compare Plans Before and After an Index

MariaDB Tutorial / Read EXPLAIN and Compare Plans Before and After an Index

Use a thousand-row fixture to compare EXPLAIN before and after indexing with the actual returned rows. Distinguish ANALYZE FORMAT=JSON execution data from statistics maintenance.

MariaDB Tutorial / Install MariaDB on Windows and Start the Server

MariaDB Tutorial / Install MariaDB on Windows and Start the Server

Set up a local MariaDB server on Windows, verify its service and TCP connection, and create a database-scoped learning account. Follow practical checks for installation, port, path, and authentication problems.

MariaDB Tutorial / Design Single and Composite Indexes for Real Queries

MariaDB Tutorial / Design Single and Composite Indexes for Real Queries

Inspect existing keys, create a customer–time composite index and review leading columns, covering access and foreign-key dependencies. Preserve query results while evaluating read, write and storage costs.

MariaDB Tutorial / Identify Rows with PRIMARY KEY, AUTO_INCREMENT, and UNIQUE

MariaDB Tutorial / Identify Rows with PRIMARY KEY, AUTO_INCREMENT, and UNIQUE

Use primary keys, generated identifiers, and unique constraints for different purposes. Practice nullable unique email values, composite keys, duplicate failures, and the identifier gap left by a rolled-back insert.

MariaDB Tutorial / Filter Rows with WHERE, AND, OR, IN, BETWEEN, and LIKE

MariaDB Tutorial / Filter Rows with WHERE, AND, OR, IN, BETWEEN, and LIKE

Build clear MariaDB filters using comparisons, grouped AND/OR conditions, IN lists, inclusive ranges and escaped LIKE patterns. Check expected product IDs and investigate missing or extra rows.

MariaDB Tutorial / Restore a Backup into a Separate Database and Verify It

MariaDB Tutorial / Restore a Backup into a Separate Database and Verify It

Review a SQL dump, restore it into a verified empty database and compare object definitions, rows and goods totals. Handle source-file errors, compatibility and partial-restoration states explicitly.

MariaDB Tutorial / Connect Python to MariaDB and Use Parameterized Queries

MariaDB Tutorial / Connect Python to MariaDB and Use Parameterized Queries

Use a complete PyMySQL program to connect, insert, select, commit, and roll back. Keep apostrophes, Unicode, and injection-shaped inputs as values, and restrict dynamic sorting through an identifier allowlist.

MariaDB Tutorial / Keep Unmatched Rows with LEFT JOIN

MariaDB Tutorial / Keep Unmatched Rows with LEFT JOIN

Retain all customers with LEFT JOIN, distinguish ON and WHERE filters, count actual right-side matches and compare no-order customers with customers lacking paid orders.