SQL INTERVAL literal
Returns an interval value written inline in SQL. PostgreSQL and Oracle quote a text literal; MySQL puts the unit keyword outside the quotes.
- Returns
interval- In this category
- 61 of 121
语法
INTERVAL '1 day' -- PostgreSQL
INTERVAL '1' DAY -- Oracle
INTERVAL 1 DAY -- MySQL
Each block is a separate form. The support table and the examples show which engine takes which.
引擎支持
| 引擎 | Support | 备注 |
|---|---|---|
| SQL Server | Not built in | no interval type; DATEADD(month, 1, d) applies spans |
| PostgreSQL | 是 | Supported under this name. |
| MySQL | Different name or syntax | INTERVAL 1 DAY syntax, no quotes around the amount |
| SQLite | Not built in | no interval type; modifiers like '+1 day' |
| Oracle | 是 | Supported under this name. |
示例
PostgreSQL
SELECT now() + INTERVAL '1 day 2 hours' AS deadline;
MySQL
SELECT created_at + INTERVAL 30 DAY AS deadline FROM orders;
Oracle
SELECT d + INTERVAL '2' HOUR AS later FROM events;
值得了解
- MySQL splits it: INTERVAL 1 DAY or INTERVAL '1' DAY; the quoted PostgreSQL form INTERVAL '1 DAY' is a syntax error there.
- Oracle needs the unit separated: INTERVAL '1' DAY, and composite literals spell the range: INTERVAL '1 2:30:00' DAY TO SECOND.
- Oracle keeps year-to-month and day-to-second intervals as separate types, so one literal cannot hold both. PostgreSQL can: INTERVAL '1 month 1 day' is valid there.
Questions about INTERVAL literal
Why does INTERVAL '1 DAY' fail on MySQL?
MySQL separates the amount from the unit: INTERVAL 1 DAY or INTERVAL '1' DAY. The whole-string PostgreSQL form does not parse there.
Can I mix months and days in one interval?
On PostgreSQL, yes: INTERVAL '1 month 1 day'. On Oracle they are separate types, so add INTERVAL '1' MONTH and INTERVAL '1' DAY in two steps. MySQL's INTERVAL takes one unit (or a compound like DAY_HOUR) per expression.
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: PostgreSQL, MySQL, 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.