SQL Server MONTH() Function
MONTH()
is a date-time function in SQL Server used to return the month part of a given date. The syntax of this function is similar to other functions and requires a date as a parameter to return the month part of that date.
Syntax
MONTH(date)
Here, the date
parameter can be a date value or an expression that contains a date, such as a column name.
Usage
MONTH()
function is typically used in queries that require grouping or sorting by month. For example, you can use this function to calculate sales by month and summarize them by month to better understand business trends.
Examples
Here are two examples of using the MONTH()
function:
Example 1
Assume there is a table named orders
that contains some orders and their creation dates. Now, we need to query the number of orders for each month to better understand the business.
SELECT MONTH(created_at) as month, COUNT(*) as orders_count
FROM orders
GROUP BY MONTH(created_at)
The above query groups all orders in the orders
table by month and calculates the number of orders for each month. The result returns a table with two columns: the first column is the month, and the second column is the number of orders for that month.
Example 2
Assume there is a table named employees
that contains some employees and their start dates. Now, we need to query all employees who started working in June or later.
SELECT * FROM employees
WHERE MONTH(start_date) >= 6
The above query filters out all employees in the employees
table who started working in June or later and returns a table with all employees who meet the criteria.
Conclusion
The MONTH()
function is a commonly used date-time function in SQL Server. It can easily extract the month part of a date and be used in various queries. If you need to group, filter, or sort data by month, the MONTH()
function can help you quickly achieve these functions.