Computers & ProgrammingBackend DevelopmentSQL

SQL DATEDIFF Function

The DATEDIFF function is used in Microsoft SQL Server to return the time between two dates/date columns.

Employees Table

employeeIDemployeeNamehireDate
1000John Smith1995-12-03
1001Fred White2001-10-12
1002Jane Scott1998-05-01
1003Samuel Williams1991-01-03

In this example, we want to find out how many days an employee has been working for the organization since their hire date.

Syntax

DATEDIFF(datepart, startDate, endDate)

DATEPART Reference Table

datepartabbreviation
yearyy, yyyy
quarterqq, q
monthmm, m
dayofyeardy, y
dayd
weekwk, ww
weekdaydw, w
hourhh
minutemi, n
secondss, s
millisecondms
microsecondmcs
nanosecondns
TZoffsettz
ISO_WEEKisowk, isoww

Example

SELECT employeeName as [Employee Name],
DATEDIFF(day,hiredate,GETDATE()) as [Total Days Since Hire]
FROM employees

Results (Query ran on 12/13/2011)

Employee NameTotal Days Since Hire
John Smith5854
Fred White3714
Jane Scott4974
Samuel Williams7649

The SQL DATEDIFF function can be very useful when you are interested in finding out how much time there is between two dates, a date, and a date field, or two date fields.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top