MySQL

How To Get Month From Date In MySQL

In this tutorial, we are going to see how to get month from date in MySQL. In SQL language MONTH() function allows extracting month number from a date in YYYY-MM-DD format. If the input date is for example ‘2022-02-03’, the output will be ‘3’. This allows associating the month number with the month name (3 = March).
 

Syntax:

To use this function you should use the following syntax:

SELECT MONTH( date );

In this SQL query, the “date” parameter can correspond to a date such as ‘2022-02-05’.
 

 

Example :

The queries below are basic examples to understand how the function works.

SELECT MONTH('2022-06-06'); --output: 6
SELECT MONTH('2022-04-01'); -- output: 4
SELECT MONTH('2022-12-01'); -- output: 12
SELECT MONTH('2022-07-07'); -- output: 7

It is important to note that the function does not return zeros for months from ’01’ to ’09’.
 

Use with the CASE statament:

It is possible to use CASE command to customize the month display directly from the SQL query. The example below compares the return value of the query to display the month name instead of a number.
 

 

SELECT CASE MONTH('2022-07-07')
         WHEN 1 THEN 'January'
         WHEN 2 THEN 'February'
         WHEN 3 THEN 'March'
         WHEN 4 THEN 'April'
         WHEN 5 THEN 'May'
         WHEN 6 THEN 'June'
         WHEN 7 THEN 'July'
         WHEN 8 THEN 'August'
         WHEN 9 THEN 'September'
         WHEN 10 THEN 'October'
         WHEN 11 THEN 'November'
         ELSE 'December'
END;

Output:

July

The result of the query will show “July” instead of the number ‘7’, which is more convenient and easier to understand for a user.
mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

Your email address will not be published. Required fields are marked *