YouTip LogoYouTip

Func Datepart

# SQL Server DATEPART() Function ## Definition and Usage The DATEPART() function is used to return a single part of a date/time, such as year, month, day, hour, minute, etc. ## Syntax ```sql DATEPART(datepart,date) ``` Where date is a valid date expression and datepart can be the following values: | datepart | Abbreviation | | ---- | ---- | | Year | yy, yyyy | | Quarter | qq, q | | Month | mm, m | | Day of year | dy, y | | Day | dd, d | | Week | wk, ww | | Weekday | dw, w | | Hour | hh | | Minute | mi, n | | Second | ss, s | | Millisecond | ms | | Microsecond | mcs | | Nanosecond | ns | ## Example 1 Assume we have the following "Orders" table: | OrderId | OrderDate | OrderPrice | Customer | | ---- | ---- | ---- | ---- | | 1 | 2008-12-29 16:25:46.635 | 1000 | Hansen | | 2 | 2008-11-15 19:20:00.635 | 1600 | Nilsen | | 3 | 2008-10-05 10:15:35.635 | 700 | Hansen | | 4 | 2008-09-25 14:13:23.635 | 300 | Hansen | | 5 | 2008-08-08 18:20:00.635 | 2000 | Jensen | | 6 | 2008-07-04 10:20:00.635 | 100 | Nilsen | Now we want to extract the year from the "OrderDate" column. We use the following SELECT statement: ```sql SELECT DATEPART(yyyy,OrderDate) AS OrderYear FROM Orders ``` The result set will look like this: | OrderYear | | ---- | | 2008 | | 2008 | | 2008 | | 2008 | | 2008 | | 2008 | ## Example 2 Now we want to extract the month from the "OrderDate" column (not just the year). We use the following SELECT statement: ```sql SELECT DATEPART(mm,OrderDate) AS OrderMonth FROM Orders ``` The result set will look like this: | OrderMonth | | ---- | | 12 | | 11 | | 10 | | 9 | | 8 | | 7 |
← Func DateaddFunc Getdate β†’