T-SQL DATEPART() Function
The T-SQL (Transact-SQL) DATEPART() function returns a specified part of a given date, as an integer value.
Syntax
DATEPART(datepart, date)
Parameters
datepart |
| ||||||||||||||||||||||||||||||||
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:
OrderQuantity | Price | OrderTime |
---|---|---|
100 | 1.58 | 2017-08-18 10:38:42 |
120 | 1.61 | 2018-03-23 07:14:16 |
125 | 1.78 | 2018-09-12 05:25:56 |
50 | 1.80 | 2019-01-16 11:52:05 |
200 | 1.72 | 2020-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:
OrderQuantity | Price | OrderTime | DATEPART_Value |
---|---|---|---|
100 | 1.58 | 2017-08-18 10:38:42 | 8 |
120 | 1.61 | 2018-03-23 07:14:16 | 3 |
125 | 1.78 | 2018-09-12 05:25:56 | 9 |
50 | 1.80 | 2019-01-16 11:52:05 | 1 |
200 | 1.72 | 2020-02-06 09:31:34 | 2 |
❮ T-SQL Functions