MySQL numeric functions
MySQL string functions
MySQL Date/Time functions
MySQL aggregate functions
MySQL flow control functions
The MONTH()
function in MySQL is a date function that returns the month for a given date. The month is returned as an integer ranging from 1 to 12.
Syntax:
MONTH(date)
Here, date
is a valid date expression.
Example:
SELECT MONTH('2023-05-12');
This will return 5
, because May is the 5th month of the year.
Usage in a Table:
Consider the following orders
table:
OrderID | Product | OrderDate |
---|---|---|
1 | Apples | 2023-05-12 |
2 | Bananas | 2023-06-15 |
3 | Oranges | 2023-07-20 |
4 | Apples | 2023-05-25 |
5 | Bananas | 2023-06-30 |
If you want to select all orders that were placed in May, you can use the MONTH()
function in the WHERE
clause:
SELECT * FROM orders WHERE MONTH(OrderDate) = 5;
This will return all rows where OrderDate
is in May:
OrderID | Product | OrderDate |
---|---|---|
1 | Apples | 2023-05-12 |
4 | Apples | 2023-05-25 |
Usage with GROUP BY
:
You can also use the MONTH()
function with the GROUP BY
clause to group orders by month. For example, if you want to count the number of orders placed in each month, you could do this:
SELECT MONTH(OrderDate) AS OrderMonth, COUNT(*) AS NumberOfOrders FROM orders GROUP BY OrderMonth;
This will return a result set with the number of orders placed in each month.
Remember that the MONTH()
function will return NULL
if the input is not a valid date expression.
MySQL MONTH Function Example:
SELECT MONTH(date_column) AS month_value FROM table_name;
How to Use MONTH Function in MySQL:
SELECT MONTH('2023-04-15') AS month_value;
Getting the Month of a Date with MONTH in MySQL:
SELECT order_id, MONTH(order_date) AS order_month FROM orders;
Extracting Month from Date Values in MySQL:
SELECT employee_name, MONTH(hire_date) AS hire_month FROM employees;
MONTH Function with WHERE Clause in MySQL:
SELECT customer_name, order_date FROM orders WHERE MONTH(order_date) = 6; -- Select orders in June
Handling NULL Values with MONTH Function in MySQL:
SELECT customer_name, MONTH(last_purchase_date) AS last_purchase_month FROM customers;
Examples of Using MONTH Function in MySQL Queries:
SELECT product_name, MONTH(release_date) AS release_month FROM products;
SELECT employee_id, MONTH(birthdate) AS birth_month FROM employees WHERE MONTH(birthdate) = 12; -- Select employees born in December
Using MONTH with Date Formatting in MySQL:
SELECT order_id, CONCAT('Month ', MONTH(order_date)) AS formatted_month FROM orders;