// dialect comparison

Interval literals for date arithmetic in SQL Server, PostgreSQL, MySQL, SQLite and Oracle

Two engines have real interval types; three fake it with functions and modifiers.

Filed under Types & casting

The verdict

If durations are data in your model (sla_hours, contract lengths), PostgreSQL and Oracle store them natively; everywhere else you store a number and a unit convention, and add via functions.

Where they differ

An interval is a duration as a value, not just an argument. PostgreSQL and Oracle have interval types you can store and multiply; MySQL has interval literals usable only in expressions; SQL Server and SQLite have neither.

How each engine writes it

SQL Server

SELECT DATEADD(HOUR, 2, DATEADD(DAY, 3, GETDATE()));

No interval type or literal: units appear only as DATEADD/DATEDIFF arguments, so a compound duration means nesting DATEADD calls. DATEDIFF between two dates is the closest thing to a duration.

PostgreSQL

SELECT NOW() + INTERVAL '3 days 2 hours';

A real interval type: literals like INTERVAL '3 days', storable in columns and multipliable (INTERVAL '1 hour' * 8). Internally one value keeps months, days and microseconds as separate fields.

MySQL

SELECT NOW() + INTERVAL '3' DAY + INTERVAL '2' HOUR;

INTERVAL n UNIT works in expressions but is not a column type. Compound units read strings: INTERVAL '1-2' YEAR_MONTH.

SQLite

SELECT DATETIME('now', '+3 days', '+2 hours');

No interval type: durations are modifier strings chained onto the date functions.

Oracle

SELECT SYSTIMESTAMP + INTERVAL '3 2:00:00' DAY TO SECOND FROM dual;

Two interval types: INTERVAL YEAR TO MONTH and INTERVAL DAY TO SECOND, both storable in columns and usable in literals like INTERVAL '1-2' YEAR TO MONTH.

Questions that come up

Can I store an interval in a column?

In PostgreSQL and Oracle yes (INTERVAL / INTERVAL DAY TO SECOND columns). MySQL, SQL Server and SQLite store numbers with an agreed unit, or two datetimes whose difference is the duration.

Why are '1 month' and '30 days' different intervals?

A month is 28 to 31 days and a day can be 23 or 25 hours across DST, so PostgreSQL stores months, days and microseconds separately and applies each against the calendar when you add the interval. Oracle goes further and makes year-month and day-second intervals two separate types that cannot be mixed.

What is the portable way to say 'one week'?

There is none: DATEADD(DAY, 7, d) in SQL Server, d + INTERVAL '7 days' in PostgreSQL, DATE_ADD(d, INTERVAL 7 DAY) in MySQL, DATE(d, '+7 days') in SQLite, d + 7 in Oracle.

Keep reading

// write it once, run it anywhere

Switch engines without relearning SQL

SQLly is a native SQL workbench for macOS, Windows and Linux. Its formatter and plan viewer work in all five dialects.