SQL MONTH

The SQL MONTH function is used to extract the month from a given date. This function is useful when analyzing data based on months, filtering records by specific months, or performing date-related calculations in SQL queries.

In this tutorial, we will cover the syntax of the MONTH function, how it works, and step-by-step examples to demonstrate its usage.


Syntax of SQL MONTH Function

The basic syntax of the MONTH function is:

</>
Copy
SELECT MONTH(date_column) 
FROM table_name;

Explanation:

  • MONTH(date_column): Extracts the month as a number (1-12) from the given date.
  • FROM table_name: Specifies the table from which the data is retrieved.

You can also use the function directly with a static date:

</>
Copy
SELECT MONTH('2024-05-15') AS month_value;

This query returns 5, as the given date falls in May.


Step-by-Step Examples Using SQL MONTH

1. Extracting the Month from a Date Column

Let’s create a employees table to demonstrate how the MONTH function works.

</>
Copy
CREATE TABLE employees (
    id INT PRIMARY KEY AUTO_INCREMENT,
    name VARCHAR(50),
    date_of_joining DATE
);

Insert some sample data:

</>
Copy
INSERT INTO employees (name, date_of_joining)
VALUES 
('Arjun', '2023-02-10'),
('Ram', '2024-07-21'),
('Priya', '2022-11-05');

Now, let’s extract the month of joining for each employee:

</>
Copy
SELECT name, date_of_joining, MONTH(date_of_joining) AS joining_month
FROM employees;

Expected Output:

Explanation:

  • The MONTH function extracts the month number (e.g., February = 2, July = 7, November = 11).
  • This helps in analyzing employee joining patterns based on months.

2. Filtering Records by a Specific Month

Suppose we want to find all employees who joined in July. We can use the WHERE clause with the MONTH function:

</>
Copy
SELECT name, date_of_joining 
FROM employees
WHERE MONTH(date_of_joining) = 7;

Expected Output:

Explanation:

  • The condition MONTH(date_of_joining) = 7 filters employees who joined in July.
  • This is useful for generating monthly reports or targeted employee queries.

Conclusion

The MONTH function in SQL is used for handling date-based queries. In this tutorial, we covered:

  1. The syntax and usage of the MONTH function.
  2. Extracting month values from a date column.
  3. Filtering records based on a specific month.