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 / Improve Date Filters, Sorting, and Pagination Without Changing Results

MariaDB Tutorial / Improve Date Filters, Sorting, and Pagination Without Changing Results

Compare equivalent date predicates and deterministic keyset pagination in MariaDB. Preserve exact results, account for version-specific DATE/YEAR optimization and review projection and search semantics.

MariaDB Tutorial / Break Queries into Named Steps with WITH and CTEs

MariaDB Tutorial / Break Queries into Named Steps with WITH and CTEs

Build a readable multi-step query with WITH, verify paid orders and per-order totals independently, and understand CTE scope, naming and execution-plan limitations.

MariaDB Tutorial / Insert One Row or Multiple Rows with INSERT

MariaDB Tutorial / Insert One Row or Multiple Rows with INSERT

Practice single-row and multi-row INSERT statements, inspect stored values and defaults, and test duplicate keys, mismatched value counts and required inputs without changing existing product tables.

MariaDB Tutorial / What MariaDB Is: Databases, SQL, and Its Relationship to MySQL

MariaDB Tutorial / What MariaDB Is: Databases, SQL, and Its Relationship to MySQL

Understand the roles of the MariaDB server and client, the structure of relational data, and the purpose of SQL. Learn how MariaDB relates to MySQL and prepare for a small product-database exercise.

MariaDB Tutorial / Create a Product Table, Insert Data, and Query It

MariaDB Tutorial / Create a Product Table, Insert Data, and Query It

Build a complete product table, insert three records, and verify its definition and query results. Practice price and stock filters, understand rerun behavior, and reset only confirmed disposable tutorial data.

MariaDB Tutorial / Calculate Running Totals and Compare Rows with LAG and LEAD

MariaDB Tutorial / Calculate Running Totals and Compare Rows with LAG and LEAD

Calculate running totals, LAG and LEAD, then compare ROWS and RANGE with tied timestamps. Verify how filtering before or after accumulation changes a period report.

MariaDB Tutorial / Choose Numeric Types: Integers, DECIMAL, FLOAT, and DOUBLE

MariaDB Tutorial / Choose Numeric Types: Integers, DECIMAL, FLOAT, and DOUBLE

Choose MariaDB numeric types by range, signedness, decimal scale, and acceptable approximation. Run a comparison of DECIMAL, FLOAT, and DOUBLE, then check rounding, overflow errors, and session-mode restoration.

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.

MariaDB Tutorial / Avoid Duplicate Totals When Joining Multiple Tables

MariaDB Tutorial / Avoid Duplicate Totals When Joining Multiple Tables

Trace row multiplication across customer, order, item and product joins. Reconcile correct goods and shipping totals, understand DISTINCT pitfalls and preaggregate details at the order grain.

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.