SQL get first day of month

This article describes how to use SQL to get the first day of the month in various databases.

Oracle

For the Oracle database, we can use the TRUNC function to truncate the date. For example:

SELECT TRUNC(date '2023-04-06', 'MM')
FROM DUAL;

| TRUNC(DATE'2023-04-05','MM') |
|------------------------------|
|         2023-04-01 00:00:00  |

The TRUNC(datetime, fmt) function can truncate the date and time based on the unit specified by fmt, and MM means truncate to the month. For other truncation units, please refer to the official documentation .

MySQL

MySQL provides the DATE_SUB and DAYOFMONTH functions, which can be used together to get the first day of the month. For example:

SET @date:='2023-04-06';
SELECT DATE_SUB(@date, INTERVAL DAYOFMONTH(@date)-1 DAY);

DATE_SUB(@date, INTERVAL day(@date)-1 DAY)|
------------------------------------------+
2023-04-01                                |

The DATE_SUB function means to subtract a time interval based on a certain date, and the DAYOFMONTH function is used to return the number of days in the month that a certain date belongs to.

Alternatively, we can also use the DATE_ADD function to achieve the same effect.

Microsoft SQL Server

The implementation method of Microsoft SQL Server is similar to MySQL, but the function name is different:

DECLARE @date date;
SET @date = '2023-04-06';
SELECT DATEADD(dd, -( DAY( @date ) -1 ), @date);

2023-04-01

The DATEADD function is used to add a time interval to the date, and the DAY function is used to return the day of the month that a date belongs to.

PostgreSQL

PostgreSQL provides a date truncation function similar to the Oracle database. For example:

SELECT date_trunc('month', date '2023-04-06')::date;

date_trunc|
----------+
2023-04-01|

The return value of the date_trunc function contains the time part, so it needs to be converted to a date type.

SQLite

The DATE function in SQLite can easily get the first day of the month, for example:

SELECT DATE('2023-04-06', 'start of month');

DATE('2023-04-06', 'start of month')|
------------------------------------+
2023-04-01                          |

Among them, "start of month" means to return the first day of the month.

Guess you like

Origin blog.csdn.net/horses/article/details/129958517