DAY() Function in SQL Server
The DAY() function in SQL Server is used to extract the day of the month from a given date. It takes a date as input and returns an integer value representing the day of the month.
Syntax:
DAY(date)
Where date
is a valid date expression.
Example:
Consider the following table named orders
:
OrderID | OrderDate |
---|---|
1 | 2021-01-15 |
2 | 2021-02-28 |
3 | 2021-03-10 |
4 | 2021-04-22 |
5 | 2021-05-05 |
To extract the day of the month from the OrderDate
column, we can use the DAY() function as follows:
SELECT OrderID, DAY(OrderDate) AS OrderDay
FROM orders;
This will return the following result:
OrderID | OrderDay |
---|---|
1 | 15 |
2 | 28 |
3 | 10 |
4 | 22 |
5 | 5 |
Alternatively, we can also use the DATEPART() function to achieve the same result:
SELECT OrderID, DATEPART(day, OrderDate) AS OrderDay
FROM orders;
This will also return the same result as above.