In MySQL, the MONTH function is used to extract the month from a date. It is particularly useful when you have a date column in your database, and you want to retrieve only the month part of it.
Syntax
The syntax for the MONTH function is quite straightforward:
MONTH(date)
Here, date is the input date from which you want to extract the month.
Example
Let’s look at a practical example. Suppose you have a table named sales with a column named order_date that contains the date when an order was placed. If you want to find out the month for each order, you can use the MONTH function in your SQL query:
SELECT order_date, MONTH(order_date) AS order_month FROM sales;
In this example, the MONTH(order_date) function will extract the month from the order_date column, and the result will be displayed in a new column named order_month. The result will be an integer between 1 and 12, representing the month of the year.
You can also use the MONTH function in conjunction with other functions or conditions in your queries. For instance, if you want to find the total sales for each month, you can use the SUM function along with the GROUP BY clause:
SELECT MONTH(order_date) AS order_month, SUM(sales_amount) AS total_sales FROM sales GROUP BY order_month;
This query groups the sales data by month and calculates the total sales for each month.
It’s important to note that the MONTH function works with date values, so if your column contains timestamps, it will still extract the month part from the timestamp.
In summary, the MONTH function in MySQL is a handy tool for extracting the month from a date column, allowing you to analyze and aggregate data based on the month component.