Interval Operator in SQL

Interval Operator in SQL

Table of contents

Introduction

  • The "interval" operator in SQL is typically used to perform operations involving date and time intervals.

  • SQL databases that support date and time data types often provide the INTERVAL keyword for constructing intervals and performing date and time calculations.

The syntax for using the INTERVAL keyword varies slightly among different database management systems (DBMSs). Below, I'll provide some common examples of how you can use the INTERVAL keyword in SQL:

  1. PostgreSQL and MySQL: In PostgreSQL and MySQL, you can use the INTERVAL keyword to construct date and time intervals. For example, to add an interval of 3 days to a date, you can use the following SQL statement:

     SELECT CURRENT_DATE + INTERVAL '3 days';
    

    You can also use INTERVAL in various date and time functions to perform calculations.

  2. SQL Server: In SQL Server, you can use the DATEADD function to add intervals to date or time values. For example, to add 3 days to a date, you can use:

     SELECT DATEADD(day, 3, GETDATE());
    

    While SQL Server doesn't use the INTERVAL keyword, it provides similar functionality for date and time operations.

  3. Oracle: Oracle Database supports the INTERVAL keyword for date and time calculations. For example, to add an interval of 2 hours and 30 minutes to a timestamp, you can use:

     SELECT TIMESTAMP '2023-10-04 12:00:00' + INTERVAL '2 30:00' HOUR TO MINUTE FROM dual;
    

    The INTERVAL keyword allows for precise control over the duration to be added or subtracted.