SQL Date Function DATEDIFF()
The DATEDIFF()
function is a built-in date function in SQL that calculates the difference between two dates. It returns the number of days, months, or years between two dates.
Here's the syntax of the DATEDIFF()
function:
DATEDIFF(interval, date1, date2)
The interval
parameter specifies the unit of time to calculate the difference between the two dates, and can be one of the following values:
day
ord
: Calculates the difference in days between the two dates.month
orm
: Calculates the difference in months between the two dates.year
ory
: Calculates the difference in years between the two dates.
The date1
and date2
parameters specify the two dates to calculate the difference between.
Here's an example of how to use the DATEDIFF()
function in a SQL query to calculate the number of days between two dates:
SELECT DATEDIFF('2022-03-15', '2022-03-01');
This query will return the number of days between the two dates, like this:
14
You can also use the DATEDIFF()
function in a WHERE
clause to filter records based on the difference between two dates, like this:
SELECT * FROM my_table WHERE DATEDIFF('day', date_column, '2022-03-15') < 30;
This query will return all records from my_table
where the difference between the value in the date_column
and the date 2022-03-15
is less than 30 days.
Note that the DATEDIFF()
function may have slightly different syntax and behavior depending on the specific SQL database system being used.