Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the last day of month in postgres?

How to find the last day os the month in postgres? I have a date columns stored as numeric(18) in the format(YYYYMMDD) I am trying it to make it date using

to_date("act_dt",'YYYYMMDD') AS "act date" 

then find the last day of this date: like this:

(select (date_trunc('MONTH',to_date("act_dt",'YYYYMMDD')) + INTERVAL '1 MONTH - 1 day')::date) 

but it gives me this error:

ERROR: Interval values with month or year parts are not supported   Detail:    -----------------------------------------------   error:  Interval values with month or year parts are not supported   code:      8001   context:   interval months: "1"   query:     673376   location:  cg_constmanager.cpp:145   process:   padbmaster [pid=20937]   ----------------------------------------------- 

Any help?

Postgres version:

PostgreSQL 8.0.2 on i686-pc-linux-gnu, compiled by GCC gcc (GCC) 3.4.2 20041017 (Red Hat 3.4.2-6.fc3), Redshift 1.0.874

like image 608
Hare Rama Hare Krishna Avatar asked Jan 28 '15 06:01

Hare Rama Hare Krishna


People also ask

How to get last day of month in Postgres?

You can select the last day of month. SELECT (date_trunc('MONTH', ('201608'||'01')::date) + INTERVAL '1 MONTH - 1 day')::DATE; 201608 is replaceable with a variable.

How do I get last 3 months Postgres?

How to get last 3 months records from the table. SELECT * from table where month > CURRENT_DATE-120 and month < CURRENT_DATE order by month; I have used the above query is it correct?

What is now () in PostgreSQL?

What is PostgreSQL Now Function? The Now() function is used to return the current date and time of the time zone (default or user-defined). Its return type is the timestamp with the time zone.


1 Answers

For anybody coming to this question looking for the Postgres way to do this (not using Redshift), here's how you'd do it:

SELECT (date_trunc('month', '2017-01-05'::date) + interval '1 month' - interval '1 day')::date AS end_of_month; 

Replacing the '2017-01-05' with whatever date you want to use. You can make this into a function like this:

create function end_of_month(date) returns date as $$ select (date_trunc('month', $1) + interval '1 month' - interval '1 day')::date; $$ language 'sql' immutable strict; 

EDIT Postgres 11+

Pulling this out of the comments from @Gabriel, you can now combine interval expressions in one interval (which makes things a little shorter):

select (date_trunc('month', now()) + interval '1 month - 1 day')::date as end_of_month;  -- +--------------+ -- | end_of_month | -- +--------------+ -- | 2021-11-30   | -- +--------------+ -- (1 row) 
like image 90
wspurgin Avatar answered Sep 21 '22 14:09

wspurgin