MySQL numeric functions
MySQL string functions
MySQL Date/Time functions
MySQL aggregate functions
MySQL flow control functions
The MONTHNAME()
function in MySQL is a date function that returns the name of the month for a given date.
Syntax:
MONTHNAME(date)
Here, date
is a valid date expression.
Example:
SELECT MONTHNAME('2023-05-12');
This will return May
, because the month in the provided date is May.
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 along with the name of the month in which they were placed, you can use the MONTHNAME()
function:
SELECT OrderID, Product, MONTHNAME(OrderDate) as Month FROM orders;
This will return:
OrderID | Product | Month |
---|---|---|
1 | Apples | May |
2 | Bananas | June |
3 | Oranges | July |
4 | Apples | May |
5 | Bananas | June |
Usage with GROUP BY
:
You can use the MONTHNAME()
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 MONTHNAME(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 MONTHNAME()
function will return NULL
if the input is not a valid date expression.
MySQL MONTHNAME Function Example:
SELECT MONTHNAME(date_column) AS month_name FROM table_name;
How to Use MONTHNAME Function in MySQL:
SELECT MONTHNAME('2023-04-15') AS month_name;
Getting the English Month Name with MONTHNAME in MySQL:
SELECT order_id, MONTHNAME(order_date) AS month_name FROM orders;
Extracting Month Names from Date Values in MySQL:
SELECT employee_name, MONTHNAME(hire_date) AS hire_month_name FROM employees;
MONTHNAME Function with WHERE Clause in MySQL:
SELECT customer_name, order_date FROM orders WHERE MONTHNAME(order_date) = 'June'; -- Select orders in June
Handling NULL Values with MONTHNAME Function in MySQL:
SELECT customer_name, MONTHNAME(last_purchase_date) AS last_purchase_month_name FROM customers;
Examples of Using MONTHNAME Function in MySQL Queries:
SELECT product_name, MONTHNAME(release_date) AS release_month_name FROM products;
SELECT employee_id, MONTHNAME(birthdate) AS birth_month_name FROM employees WHERE MONTHNAME(birthdate) = 'December'; -- Select employees born in December
Using MONTHNAME with Date Formatting in MySQL:
SELECT order_id, CONCAT('Month: ', MONTHNAME(order_date)) AS formatted_month_name FROM orders;