SQL Server Tutorial SQL Server Advanced SQL Server Database SQL Server References

SQL Server DATEPART() Function



The SQL Server (Transact-SQL) DATEPART() function returns a specified part of a given date, as an integer value.

Syntax

DATEPART(datepart, date)

Parameters

datepart

Required. Specify the unit type to retrieve from the date. It can be one of the following values:

datepartAbbreviations
yearyy, yyyy
quarterqq, q
monthmm, m
dayofyeardy, y
daydd, d
weekwk, ww
weekdaydw, w
hourhh
minutemi, n
secondss, s
millisecondms
microsecondmcs
nanosecondns
tzoffsettz
iso_weekisowk, isoww
date Required. Specify a date to use to retrieve the datepart value.

Return Value

Returns an integer representing the specified datepart of the specified date.

Example 1:

The example below shows the usage of DATEPART() function.

SELECT DATEPART(year, '2019-10-25');
Result: 2019

SELECT DATEPART(yyyy, '2019-10-25');
Result: 2019

SELECT DATEPART(yy, '2019-10-25');
Result: 2019

SELECT DATEPART(quarter, '2019-10-25');
Result: 4

SELECT DATEPART(month, '2019-10-25');
Result: 10

SELECT DATEPART(week, '2019-10-25 08:10:25');
Result: 43

SELECT DATEPART(day, '2019-10-25');
Result: 25

SELECT DATEPART(hh, '2019-10-25 08:10:25');
Result: 8

SELECT DATEPART(hh, '2019-10-25 08:10:25');
Result: 8

SELECT DATEPART(mi, '2019-10-25 08:10:25');
Result: 10

SELECT DATEPART(ss, '2019-10-25 08:10:25');
Result: 25

Example 2:

Consider a database table called Orders with the following records:

OrderQuantityPriceOrderTime
1001.582017-08-18 10:38:42
1201.612018-03-23 07:14:16
1251.782018-09-12 05:25:56
501.802019-01-16 11:52:05
2001.722020-02-06 09:31:34

The statement given below can be used to get the month portion of records of column OrderTime:

SELECT *, DATEPART(month, OrderTime) AS DATEPART_Value FROM Orders;

This will produce the result as shown below:

OrderQuantityPriceOrderTimeDATEPART_Value
1001.582017-08-18 10:38:428
1201.612018-03-23 07:14:163
1251.782018-09-12 05:25:569
501.802019-01-16 11:52:051
2001.722020-02-06 09:31:342

❮ SQL Server Functions