SQL MONTH() Function
Overview
This article focuses on the understanding and usage of the SQL MONTH() function that is used in query languages.
Introduction to SQL MONTH()
The SQL MONTH() function returns the month of the date as an integer (a number from 1 to 12). We can either provide a datetime or date to get the month.
Syntax
The syntax of the SQL MONTH() function is as follows:
The keyword MONTH is written with parenthesis inside which one required parameter is passed.
Parameters/Arguments
We have already seen the syntax of the SQL MONTH() function. It is easier to guess the argument passed to the function:
Argument Passed | Description |
---|---|
Date/DateTime | It is a required parameter. We specify the date/datetime from which we want to extract the month. |
Return Value
There can be three types of the argument passed to the SQL MONTH() function:
- Date Type - When a date is passed to the function, it returns an integer between 1-12 where the numbers specify each month in numeric form.
- Time Type - When only a time value is passed to the function, the function returns 1.
- DateTime Type - When a datetime value is passed to the function, it works similarly as when we pass a value with only the date part.
How to use SQL MONTH()
There are multiple scenarios where the SQL MONTH() function facilitates our queries. Let us go through them one by one:
Example 1: Passing DateTime Argument to the Function
We know that argument can be of datetime type, hence let's see the output when a datetime parameter is passed to the function:
The above function will return integer 9.
Example 2: Passing a Time Argument to the Function
A unique scenario where the SQL compiler always returns 1 is when we only pass the time part of the datetime:
The above function will return integer 1.
Features of SQL MONTH()
There are some features of the SQL MONTH () function:
- It is used to extract the monthly data of the year for the argument passed.
- The function can accept time along with the date as an argument.
- It is a date function in SQL.
- Only one required parameter is passed to the function.
Conclusion
- The SQL MONTH() function returns the month as an integer for the specified date.
- There is only one argument passed that is required. The argument passed is of date type.
- When the argument passed is of date/datetime type, an integer between 1-12 is returned. Whereas, if only time is passed to the function, it returns 1 always.