SQL Server provides powerful functions for manipulating date and time data. Often, you’ll need to extract specific components – like the hour, minute, or day – from a datetime or datetime2 value. This tutorial explains how to achieve this using the DATEPART function.
Understanding DATEPART
The DATEPART function allows you to retrieve a specific part of a date or time value. It takes two arguments:
-
datepart: A string or integer specifying the date or time component you want to extract. Common values include:yearoryyoryyyyquarterorqqorqmonthormmormdayofyearordyorydayorddordweekorwkorwwweekdayordworwhourorhhminuteormiornsecondorssorsmillisecondormsmicrosecondormcsnanosecondorns
-
date: Thedatetimeordatetime2value from which you want to extract the component. This can be a column name, a variable, or a literal date/time value.
Examples
Let’s illustrate how to use DATEPART with different components.
-
Extracting the Hour:
SELECT DATEPART(hour, GETDATE());This query retrieves the current hour (0-23) from the system’s current date and time.
GETDATE()returns the current datetime. -
Extracting the Month:
SELECT DATEPART(month, '2024-10-26');This query will return
10, representing the month of October. -
Extracting the Day:
SELECT DATEPART(day, '2024-10-26');This query will return
26, representing the day of the month. -
Using
DATEPARTin aWHEREclause:SELECT * FROM Orders WHERE DATEPART(hour, OrderDate) = 10;This query selects all orders placed at 10:00 AM.
-
Extracting multiple components:
You can extract multiple components in a single query:
SELECT DATEPART(year, OrderDate) AS OrderYear, DATEPART(month, OrderDate) AS OrderMonth, DATEPART(day, OrderDate) AS OrderDay FROM Orders;
Important Considerations
DATEPARTreturns an integer representing the extracted component.- The
datepartargument is case-insensitive.hourandHOURare equivalent. DATEPARTworks with bothdatetimeanddatetime2data types.- When using
DATEPARTin aWHEREclause, consider indexing the column you are filtering on to improve query performance.