Get FIRST DAY AND LAST DAY OF A MONTH IN Postgresql

Below is the functions to get first day and last day of month in PostgreSQL.

To get first day of month, below is the plpgsql function, this function take the date value as input and return the first day of that month.

CREATE OR REPLACE FUNCTION first_day(date)
RETURNS date AS
$$
SELECT (date_trunc('MONTH', $1))::date;
$$ LANGUAGE 'sql'
IMMUTABLE STRICT;

part=# select first_day('2020-07-03');
 first_day
------------
 2020-07-01
(1 row)

To get the last of month, below is the plpgsql function, this function take the date value as input and return the last day of month.

CREATE OR REPLACE FUNCTION last_day(date)
RETURNS date AS
$$
SELECT (date_trunc('MONTH', $1) + INTERVAL '1 MONTH - 1 day')::date;
$$ LANGUAGE 'sql'
IMMUTABLE STRICT;

part=# select last_day('2020-07-03');
  last_day
------------
 2020-07-31
(1 row)

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s