How to Extract Month from Date in SQL?
In this article, we'll learn how to extract the month from a date in SQL. We will discuss three different ways to do this. We will use: MONTH(), DATEPART(), and FORMAT() to extract the month part of a date in SQL.
Let's look into the three different ways in which we can extract a month from a date:
Using the MONTH() function is the most straightforward way to extract the month part of a date in SQL. The MONTH() function takes one argument date and returns the month part of the specified date.
This function will give output in the form of an integer corresponding to the month.
The DATEPART() function takes two arguments, the first argument is the part of the date that you want to extract(month or day, or year), and the second one is the date from which you want to extract that part.
Note: We can also use mm or m in place of the month as the first argument.
The FORMAT() function formats a value the way you want. It takes three arguments, the first and second ones are mandatory. The first argument is the value we want to format, and the second argument is the pattern in which we want to format the value.
Examples to Extract Month from Date in SQL
Example 1: Using MONTH()
In the above example, we are using a straightforward method. We are directly passing the date in the MONTH() function and storing it in the column as Month using AS and getting the output for the month in number.
Example 2: Using a variable in MONTH()
In this example, we took a different approach. Instead of directly specifying the date in the function, we use a variable and put the date in it.
Example 3: Using DATEPART()
Here, we are using the DATEPART() function. As discussed above, this function takes two arguments. Here also, we can either pass the date directly or we can use a variable as we have done in the above example.
Example 4: Using FORMAT()
The FORMAT() function is used to format values according to the specified format declared in the argument of the function. It takes three arguments, two of which are mandatory. The first argument takes the value to be formatted and the second argument is the format pattern.
In this article, we learned how to extract a month from a date in SQL. We saw three different methods:
Each of these functions has its features and we use them accordingly.
Extracting a piece of data from a collection of information is used often. We should know different methods through which we can achieve it. In this article, we learned an important skill of retrieving monthly data from a specific date.