The INTERVAL data type is used in SQL to represent a span of time. It can be used to store a duration that can be added to or subtracted from a timestamp. The INTERVAL type is particularly useful for calculations involving time, such as determining the difference between two dates or adding a specific duration to a date.
Key Features:
- Components: An
INTERVALcan represent a duration in terms of years, months, days, hours, minutes, and seconds. - Syntax: The syntax for defining an
INTERVALcan vary slightly between SQL databases, but a common format is:
WhereINTERVAL 'value unit'valueis a number andunitcan be one of the following:YEAR,MONTH,DAY,HOUR,MINUTE,SECOND.
Example Usage:
-
Creating an Interval:
SELECT INTERVAL '1 DAY' AS one_day; -
Adding an Interval to a Timestamp:
SELECT CURRENT_TIMESTAMP + INTERVAL '2 HOURS' AS new_time; -
Calculating the Difference Between Two Dates:
SELECT end_date - start_date AS duration FROM your_table;
Important Notes:
- The exact syntax and capabilities of the
INTERVALtype may vary between different SQL databases (like PostgreSQL, MySQL, Oracle, etc.), so it's important to refer to the specific documentation for your database system for details on how to use it effectively.
