In MySQL, the MONTH() is a built-in function that helps to extract or retrieve the month value from a given date value. It returns a numerical representation of the month value between 1 to 12. This function can be used to perform various tasks such as filtering data based on specific months or analyzing date data. Whether you’re working with static or dynamic date values in a database, the MONTH() function can be a great resource to help you manipulate and analyze your data effectively.
This guide will explain what the MONTH() function is and how it works in MySQL.
What Does MONTH() Function Do in MySQL?
The “MONTH()” function can be utilized to get the month value in a numerical form (between 1 to 12), from a given date value. The following is the syntax of the MONTH() function:
In the above syntax, the “date” is the date value.
Let’s explore a few examples to understand what the MONTH() function does in MySQL.
Example 1: Extract Month Value From a Static Date Value
The “MONTH()” function can be utilized to extract or retrieve the month value from the static date value. The example is given below:
Output
The output showed that the month value “4” has been extracted from a static date value “2023-04-15”.
Example 2: Extract Month Value From a Current DateTime Value
The current date-time value can be retrieved by using the “NOW()” function. To retrieve the month value from today’s DateTime, the “MONTH()” function can be utilized as follow:
Output
The output showed the current month’s value.
Example 3: Extract the Month Value From a Table’s Date
To retrieve the month value from the table’s data, the “MONTH()” function can be utilized. The example of getting the month value from the “joineddate” column of the “lh_data” table is given below:
FROM lh_data;
Output
The output showed the month value of the “joineddate” column with the name column of the “lh_data” table.
Example 4: Use MONTH() Function for a Condition
The “MONTH()” function can be utilized for a condition with the “WHERE” clause to filter the particular data. An example of filtering data based on the condition of “lh_data” tables is given below:
WHERE MONTH(joineddate) BETWEEN 2 AND 4;
In the above example, the condition is that the month value in a “joineddate” column must be between “2” and “4”.
Output
The output showed the data of those employees whose “joineddate” is between months 2 to 4.
Conclusion
The “MONTH()” function in MySQL is a useful tool to extract or retrieve the month value from a provided date value. It can be used with static date values, current date-time values, and table date values. Additionally, it can also be utilized with a WHERE clause to filter out the data, based on particular month values. This guide has explained what the MONTH() function is and how it works in MySQL.