MONTH

The SQL MONTH function is a built-in function that is used to extract the month from a given date value. The MONTH function is available in most SQL database management systems and is particularly useful for handling date-related queries.

Syntax

The syntax for the SQL MONTH function is straightforward. It takes a date value as its argument and returns an integer value representing the month of the year. The function syntax is as follows:

MONTH(date)

Here, date is the date value from which we want to extract the month. This argument can be a date literal, a column of a table that contains date values, or an expression that returns a date value.

The return value of the MONTH function is an integer value between 1 and 12, representing the month of the year. For example, if the input date is ‘2021-09-12’, the MONTH function will return the value 9, indicating that the month is September.

The SQL MONTH function can be used in various scenarios, such as filtering data based on the month, grouping data by the month, or extracting the month from a date value in a report.

Example

Here’s an example that uses the MONTH function to extract the month from a date column in a table:

SELECT 
MONTH(OrderDate) as Month, 
SUM(TotalAmount) as TotalSales
FROM Orders
WHERE YEAR(OrderDate) = 2022
GROUP BY MONTH(OrderDate)

This SQL query retrieves the total sales for each month in the year 2022. It uses the MONTH function to extract the month from the OrderDate column, and the SUM function to calculate the total sales for each month. Finally, the result set is grouped by the month.

In conclusion, the SQL MONTH function is a powerful tool for handling date-related queries. It simplifies the process of extracting the month from a date value, which can be used in various SQL statements.