SQL interval arithmetic
Durations support real math: interval + interval, interval * n, date - interval, as long as you respect the month/day/second field split.
- Returns
interval / timestamp- In this category
- 116 of 121
语法
d - INTERVAL '1 day'
iv1 + iv2
iv * 2.5
Each block is a separate form. The support table and the examples show which engine takes which.
引擎支持
| 引擎 | Support | 备注 |
|---|---|---|
| SQL Server | Different name or syntax | DATEADD per part; no interval values to do math on |
| PostgreSQL | 是 | full arithmetic on intervals |
| MySQL | Different name or syntax | per-call INTERVAL terms, no interval values |
| SQLite | Different name or syntax | modifier chains only |
| Oracle | 是 | intervals add and scale; DATE math is days |
示例
PostgreSQL
SELECT now() - INTERVAL '90 minutes';
PostgreSQL
SELECT INTERVAL '45 minutes' * 2; -- 01:30:00
Oracle
SELECT TIMESTAMP '2026-08-01 00:00:00' - INTERVAL '2' DAY FROM dual; -- 2026-07-30 00:00:00
值得了解
- PostgreSQL stores months, days and seconds separately: INTERVAL '1 month' + INTERVAL '30 days' keeps both parts, and EXTRACT(EPOCH) then assumes 30 days per month; do epoch math only when that assumption is fine.
- Multiplication and division push fractions down but never carry up: INTERVAL '3 days' / 2 is 1 day 12:00:00 and INTERVAL '1 month' / 2 is 15 days, yet INTERVAL '20 hours' * 2 stays 40:00:00. justify_interval() does the carrying.
- Oracle DATE arithmetic works in days (d - 7), and DATE + INTERVAL works too: DATE '2026-08-01' + INTERVAL '1 02:30:00' DAY TO SECOND is 2026-08-02 02:30. Adding a month interval to a 31st errors (ORA-01839) instead of clamping.
Questions about Interval arithmetic
Why is my interval average showing days and hours mixed oddly?
Averaging keeps each field separate and may leave out-of-range values; wrap with justify_interval(avg(iv)) or justify_hours to carry into sensible fields.
Can I multiply intervals in SQL Server?
No interval values exist; multiply the unit count first: DATEADD(MINUTE, 45 * 2, d).
Browse every function in the SQL function reference, or see what the SQLly desktop app does for your database.
Related on SQLly
Cheat sheets for the engines that have it: SQL Server, PostgreSQL, MySQL, SQLite, Oracle.
Functions your engine actually has
SQLly's completion lists the built-in functions of the engine you're connected to, whether that's SQL Server, PostgreSQL, MySQL, SQLite or Oracle. Hover a function for help, and signature hints show each argument as you type.