MySQL MONTH Function

MySQL MONTH Function

MySQL MONTH() Function

The MONTH() function in MySQL extracts the month (as a number) from a given date or datetime value. It returns an integer between 1 (January) and 12 (December).

Syntax

MONTH(date)

Parameter:

  • date: A valid DATE, DATETIME, or TIMESTAMP value from which the month will be extracted.

Return Value:

  • Returns an integer (1-12) representing the month.
  • Returns NULL if the input is NULL or an invalid date.

Examples

1. Extracting the Month from a Date

SELECT MONTH('2025-07-15') AS month_number;

Output:

+--------------+ | month_number | +--------------+ | 7 | +--------------+

2. Extracting the Month from a Datetime

SELECT MONTH('2025-12-25 14:30:00') AS month_number;

Output:

+--------------+ | month_number | +--------------+ | 12 | +--------------+

3. Using MONTH() on a Table Column

Assume we have a orders table:

SELECT order_id, order_date, MONTH(order_date) AS order_month FROM orders;

This query will return the order month for each order.

4. Using MONTH() in a WHERE Clause

Find all records from July:

SELECT * FROM orders WHERE MONTH(order_date) = 7;

Handling NULL and Invalid Dates

SELECT MONTH(NULL) AS result; -- Output: NULL SELECT MONTH('2025-15-30') AS result; -- Output: NULL (Invalid Date)

Alternative: Getting the Month Name

If you need the month name instead of the number, use MONTHNAME():

SELECT MONTHNAME('2025-07-15') AS month_name;

Output:

+------------+ | month_name | +------------+ | July | +------------+

Conclusion

  • MONTH() is useful for extracting the month as a number (1-12).
  • Can be used in SELECT, WHERE, and other SQL clauses.
  • Use MONTHNAME() if you need the full month name instead.

This function is great for filtering and grouping data based on months! šŸš€

Soeng Souy

Soeng Souy

Website that learns and reads, PHP, Framework Laravel, How to and download Admin template sample source code free.

Post a Comment

CAN FEEDBACK
close