MySQL QUARTER() Function

Summary: in this tutorial, you will learn how to use the MySQL QUARTER() function to get the quarter of the year for a specific date.

Introduction to MySQL QUARTER() function

The QUARTER() function allows you to get the quarter of the year for a specific date.

Here’s the syntax of the QUARTER() function:

QUARTER(date)Code language: SQL (Structured Query Language) (sql)

In this syntax:

  • date: This is the date for which you want to get the quarter.

The QUARTER() function returns an integer from 1 to 4, which represents the quarter of the year for the date.

If the date is NULL, the QUARTER() function returns NULL.

The QUARTER() function is useful in data analytic applications. For example, you can use it in the sales and finance application to analyze the sales, revenues, and expenses by quarters.

MySQL QUARTER() function examples

Let’s take some examples of using the QUARTER() function.

1) Simple QUARTER() function example

The following example uses the QUARTER() function to return the quarter of the date '2023-10-18':

SELECT QUARTER('2023-10-18');Code language: SQL (Structured Query Language) (sql)

Output:

+-----------------------+
| quarter('2023-10-18') |
+-----------------------+
|                     4 |
+-----------------------+
1 row in set (0.01 sec)Code language: SQL (Structured Query Language) (sql)

Similarly, the following statement returns the quarter of the current date:

SELECT QUARTER(NOW());Code language: SQL (Structured Query Language) (sql)

2) Using the QUARTER() function with table data

We’ll use the orders table from the sample database:

MySQL QUARTER() function - Sample Table

The following example uses the QUARTER() function to get the order count for each quarter of the year 2004:

SELECT 
  QUARTER(orderDate) quarter, 
  COUNT(*) orderCount 
FROM 
  orders 
WHERE 
  year(orderDate) = 2004 
GROUP BY 
  QUARTER(orderDate);Code language: SQL (Structured Query Language) (sql)

Output:

+---------+------------+
| quarter | orderCount |
+---------+------------+
|       1 |         27 |
|       2 |         30 |
|       3 |         35 |
|       4 |         59 |
+---------+------------+
4 rows in set (0.00 sec)Code language: SQL (Structured Query Language) (sql)

In this example, we use the QUARTER() function to extract the quarter from the orderDate for each order, and then group the orders by the quarter.

Summary

  • Use the QUARTER() function to get the quarter of the year from a specific date.
Was this tutorial helpful?