MySQL MariaDB

How to Use the QUARTER() Function in MySQL?

QUARTER() is a built-in function in MySQL that can be utilized to extract the quarter value (between 1 and 4) from a specific date. This function can be utilized to simplify the process of filtering and retrieving data based on quarters. It is essential for businesses that require data analysis and forecasting based on quarters.

This post will explore various use cases of the QUARTER() function in MySQL.

How to Utilize the QUARTER() Function in MySQL?

The “QUARTER()” function in MySQL is utilized to return the quarter of a year (between 1 and 4) by taking the input as a date. The syntax of the QUARTER() function is given below:

QUARTER(date)

 

In the above syntax, “date” represents any valid date value.

Let’s move to the examples to analyze the usage of the QUARTER() function in MySQL.

Example 1: Extract Quarter Value From Static Date Value

In MySQL, the “QUARTER()” is a function that can be utilized to extract the quarter (1-4) from the given static date value. An example of retrieving the quarter value from a date is given below:

SELECT QUARTER('2023-01-10');

 

Output

The output showed the quarter value of the given date.

Let’s try with another month’s value as follow:

SELECT QUARTER('2022-10-01');

 

Output

This time the output is “4” because the date was “2022-10-01” and that is in the 4th quarter of the year.

Example 2: Extract the Quarter Value From the Tables Data

The “QUARTER()” function can be utilized to retrieve the quarter value from the specified column of a table. The example of getting the quarter value of the “joineddate” column of the “lh_data” table is given below:

SELECT id, name, joineddate, QUARTER(joineddate)
FROM lh_data;

 

Output

The output showed the quarter value with the column value of the “lh_data” table.

Example 3: Use QUARTER() Function With WHERE Clause

The “QUARTER()” function can be utilized with the “WHERE” clause to filter the table’s data based on the quarter. The example of filtering the “lh_data” tables is given below:

SELECT *
FROM lh_data
WHERE QUARTER(joineddate) = 2;

 

In the above example, a condition is specified to get the 2nd quarter values.

Output

The output shows the 2nd quarter values.

Conclusion

The “QUARTER()” function in MySQL is a useful tool for retrieving the quarter value from a date value. By using this function, it is easy to extract the quarter value from the date value and filter data based on the quarter. In this blog post, MySQL’s QUARTER() function is explained using various examples.

About the author

Danish Ghafoor

I am a computer science graduate with a certification in cybersecurity. My passion for technology has led me to develop a deep understanding of the challenges and solutions in the field of information security. I am dedicated to staying up-to-date with the latest industry trends and technologies, and constantly seeking out new opportunities to expand my knowledge and skills.