How to Get First Day of Every Corresponding Month in MySQL?
Last Updated :
14 Jun, 2024
In the MySQL database, we generally need to get the first day of a month from a certain date. While there are many tasks related to dates, one key job is figuring out the first day of each month is an important need. This is important in many places like finance reports or schedules.
This is usual for data analysis and reports. Getting the first day of every month in MySQL is very important for date-oriented tasks. In this article, we will learn how to get the first day in every corresponding month in MySQL using date functions.
How to Retrieve the First Day of the Month in MySQL
Extracting the first day of the month in MySQL is a common requirement for date-oriented tasks. Here, we'll explore three approaches to achieve this efficiently.
- Using the DATE_FORMAT() Function
- Using the CONCAT() and STR_TO_DATE() Functions
- Using the DATE_SUB() and LAST_DAY() Functions
Let's Setup an Environment
Let's create a table named students to perform the examples for all the three approaches:
CREATE TABLE students (
id int PRIMARY KEY NOT NULL AUTO_INCREMENT,
name varchar(50) DEFAULT NULL,
age int DEFAULT NULL,
grade varchar(2) DEFAULT NULL,
joining date DEFAULT NULL
)
Using the DATE_FORMAT() Function
The DATE_FORMAT() function in MySQL allows formatting dates according to specific patterns. It's commonly used to manipulate date representations, enabling tasks like extracting the first day of the month efficiently.
Syntax:
DATE_FORMAT(DATE_ADD(date_column, INTERVAL 1 - DAYOFMONTH(date_column) DAY), '%Y-%m-01') AS first_day
Example: Using the DATE_FORMAT() Function
In this approach, we will manipulate the date using DATE_FORMAT() and DATE_ADD() functions to format it as the first day of a month.
SELECT
name,
joining,
DATE_FORMAT(DATE_ADD(joining, INTERVAL 1 - DAYOFMONTH(joining) DAY), '%Y-%m-01') AS first_day
FROM
students limit 4;
Output:
Using the DATE_FORMAT() Function OutputExplanation:
- The DATE_ADD() is used to add or subtract days from the joining date to get the first day of that month.
- This function returns an integer representing the day of the month for the given date.
- The DATE_FORMAT() formats generates a “YYYY-MM-01” string which represents the starting day of a month.
Using the CONCAT() and STR_TO_DATE() Functions
Syntax:
CONCAT(YEAR(date_column), '-', MONTH(date_column), '-01') AS first_day
Example: Using the CONCAT() and STR_TO_DATE() Functions
In this particular method, to create a string that represents the first day of the month, we shall use CONCAT() function along with STR_TO_DATE() function.
SELECT
name,
joining,
STR_TO_DATE(CONCAT(YEAR(joining), '-', MONTH(joining), '-01'), '%Y-%m-%d') AS first_day
FROM
students limit 4;
Output:
Using the CONCAT() and STR_TO_DATE() Functions OutputExplanation:
- This string, ‘concat(year(joining)), “-“, month(Joining), “-01”)’ will creating a string in the format of ‘YYYY-MM-01’ that represents the first day of the month.
- STR_TO_DATE() changes this string into a date format.
Using the DATE_SUB() and LAST_DAY() Functions
Syntax:
DATE_SUB(LAST_DAY(date_column), INTERVAL DAY(LAST_DAY(date_column)) - 1 DAY) AS first_day
Example: Using the DATE_SUB() and LAST_DAY() Functions
We will use the DATE_SUB() to extract month and year from the joining date, and LAST_DAY() for getting last day of the month. Then we can take away subtract 1 from day of the month to get first day.
SELECT
name,
joining,
DATE_SUB(LAST_DAY(joining), INTERVAL DAY(LAST_DAY(joining)) - 1 DAY) AS first_day
FROM
students LIMIT 4;
Output:
Using the DATE_SUB() and LAST_DAY() Functions OutputExplanation:
- LAST_DAY(joining): this function returns the last day of the month for joining date.
- DAY(LAST_DAY(joining)): this extracts the day from the date that is found at step before
- INTERVAL DAY(LAST_DAY(joining)) - 1 DAY: here we calculate the number of days that have to be subtracted from the last day to reach 1st day
- DATE_SUB(): this subtracts calculated duration from last day of the month and gives us first day.
Conclusion
To get the first day of each month from a date in MySQL, by using techniques like DATE_FORMAT(), manipulating strings with CONCAT() and STR_TO_DATE() functions, or applying DATE_SUB() and LAST_DAY() functions, you can have flexibility and accuracy in manipulating dates. These functions help in getting out this information for data analysis and reports. The examples and concept in this article can help you to use this method in your MySQL searches to carry out date analysis.
Similar Reads
How to Get the First Day of the Month in PL/SQL?
In PL/SQL programming, efficiently manipulating dates is crucial for various tasks, such as generating reports, calculating durations, or scheduling events. One common requirement is retrieving the first day of the month from a given date. In this article, we'll explore different approaches to achie
4 min read
How to Get Number of Days in Current Month in PHP?
This article will show you how to get the number of days in the current month in PHP. In PHP, you may need to find the number of days in the current month for various purposes, such as generating a calendar or performing date calculations. There are three approaches to get the number of days in the
3 min read
How to Convert Rows into Columns in MySQL?
Converting rows into columns, also known as pivoting or transposing, is a common operation in DBMS, and MySQL provides robust functionality for achieving this transformation. This process is useful to reshape data for better analysis or reporting. This guide will explore the syntax, usage, and examp
3 min read
How to to Get Number of Days in Current Month in Moment.JS?
While working with dates in JavaScript, sometimes we need to find the number of days in the current month. For example, February has 28 or 29 days depending on whether it's a leap year or not, while other months have 30 or 31 days. Moment.js is a powerful JavaScript library that makes handling dates
2 min read
SQL Query to Get First and Last Day of a Month in a Database
In SQL, working with date and time data is critical for tasks like reporting, scheduling, and data analysis. Determining the first and last day of a month is a common requirement. SQL provides powerful functions like DATE_SUB, DAYOFMONTH, and LAST_DAY to make these calculations straightforward.In th
4 min read
How to Group by Month and Year in MySQL?
GROUP BY clause is an essential feature for data analysis. It enables users to aggregate information based on specific criteria. To group records based on day, month, and year, we can use DAY(), MONTH(), and YEAR() functions respectively. In this article, we will look at how to use MySQLâs GROUP BY
4 min read
How to Strip Time Component From Datetime in MySQL?
MySQL is a very popular open-source and free database server that is ideal for small and large applications and is a relational database management system where SQL (Structured Query Language) queries or statements are used to manage and manipulate the data. MySQL provides many built-in functions li
4 min read
How to find the first Monday of a given month using NumPy?
To find the first Monday of a given month, we are going to use the numpy module i.e the numpy.busday_offset() method in numpy module. Syntax: np.busday_offset('date', 0, roll='forward', weekmask='Mon') Parameters: date: The array of dates to process. offsets: The array of offsets, which is broadcast
2 min read
How to Store Multiple Dates in a Column in MySQL
In MySQL databases, storing multiple dates within a single column can be a requirement when dealing with scenarios such as event schedules, recurring tasks, or historical records. Understanding how to effectively manage and query multiple dates from a single column is crucial for optimizing database
4 min read
How to Get Last Day of Previous Month From Date in Moment.JS?
To get the last day of the previous month from a given date in Moment.js, you need to adjust the date to the start of the current month and then subtract one day. This approach allows you to accurately find the final day of the previous month regardless of varying month lengths.Installing Moment.js
2 min read