You can use the following syntax to get the first day of the quarter for a given date in MySQL:
SELECT sales_date, MAKEDATE(YEAR(sales_date), 1) +
INTERVAL QUARTER(sales_date) QUARTER -
INTERVAL 1 QUARTER AS first_day
FROM sales;
This particular example creates a new column named first_day that contains the first day of the quarter for the corresponding date in the sales_date column of the table named sales.
The following example shows how to use this syntax in practice.
Example: How to Get First Day of Quarter in MySQL
Suppose we have the following table named sales that contains information about sales made at various grocery stores on various dates:
-- create table
CREATE TABLE sales (
store_ID INT PRIMARY KEY,
item TEXT NOT NULL,
sales_date DATE NOT NULL
);
-- insert rows into table
INSERT INTO sales VALUES (0001, 'Oranges', '2024-02-10');
INSERT INTO sales VALUES (0002, 'Apples', '2024-11-25');
INSERT INTO sales VALUES (0003, 'Bananas', '2024-07-30');
INSERT INTO sales VALUES (0004, 'Melons', '2024-01-14');
INSERT INTO sales VALUES (0005, 'Grapes', '2024-05-19');
-- view all rows in table
SELECT * FROM sales;
Output:
+----------+---------+------------+
| store_ID | item | sales_date |
+----------+---------+------------+
| 1 | Oranges | 2024-02-10 |
| 2 | Apples | 2024-11-25 |
| 3 | Bananas | 2024-07-30 |
| 4 | Melons | 2024-01-14 |
| 5 | Grapes | 2024-05-19 |
+----------+---------+------------+
Suppose that we would like to select the dates from the sales_date column and create a new column that contains the first day of the quarter for each corresponding date in the sales_date column.
We can use the following syntax to do so:
SELECT sales_date, MAKEDATE(YEAR(sales_date), 1) +
INTERVAL QUARTER(sales_date) QUARTER -
INTERVAL 1 QUARTER AS first_day
FROM sales;
Output:
+------------+------------+
| sales_date | first_day |
+------------+------------+
| 2024-02-10 | 2024-01-01 |
| 2024-11-25 | 2024-10-01 |
| 2024-07-30 | 2024-07-01 |
| 2024-01-14 | 2024-01-01 |
| 2024-05-19 | 2024-04-01 |
+------------+------------+
Notice that the dates in the first_day column represent the first day of the quarter for the corresponding date in the sales_date column.
For example:
- The first day of the quarter for the date 2/1/2024 is 1/1/2024.
- The first day of the quarter for the date 11/25/2024 is 10/1/2024.
- The first day of the quarter for the date 7/30/2024 is 7/1/2024.
And so on.
Additional Resources
The following tutorials explain how to perform other common tasks in MySQL:
MySQL: How to Return All Rows Between Two Dates
MySQL: How to Return All Rows Greater Than Date
MySQL: How to Select Rows where Date is Equal to Today