DATEDIFF Function - SQL


Overview


The DATEDIFF function in SQL returns the difference in days between two dates. It is useful for calculating the number of days between two date expressions.

Example:

SELECT DATEDIFF('2024-01-11', '2024-01-01')

Syntax:

SELECT DATEDIFF(end_date, start_date)

end_date is the later date.

start_date is the earlier date.

Sample Data:

first_name birthday
Frank 1994-03-15 00:00:00
Jane 1980-06-14 00:00:00
Ashley 1975-12-05 00:00:00
Glenn 1988-03-23 00:00:00
Kelly 1979-10-11 00:00:00
Richard 1985-08-30 00:00:00
George 1992-02-18 00:00:00
Kyle 1983-04-07 00:00:00
James 1978-09-27 00:00:00
Gustavo 1987-11-21 00:00:00

Example: Hard-coded value


In this example, we are returning the difference between the date ‘2024-01-11’ and ‘2024-01-01,’ the final output is 10.


Example: Query without the WHERE Statement


In this example, we are returning the difference between the birthday column and the ‘2024-01-01’ date.


Example: Query with the WHERE Statement


In this example, we are returning the difference between the birthday column and the ‘2024-01-01’ date where the first_name column equals ‘Kelly.’