Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I determine the last day of the previous month using PostgreSQL?

I need to query a PostgreSQL database to determine records that fall within today's date and the last day of the previous month. In other words, I'd like to retrieve everything that falls between December 31, 2011 and today. This query will be re-used each month, so next month, the query will be based upon the current date and January 31, 2012.

I've seen this option, but I'd prefer to avoid using a function (if possible).

like image 897
Huuuze Avatar asked Jan 20 '12 16:01

Huuuze


People also ask

How do you get the last date of the 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 the last day of the month in SQL?

If you would like to get the date containing the last day of the month of a given date, use the EOMONTH() function. This function takes one mandatory argument: a date (or date and time), which can be a date/datetime column or an expression that returns a date. (In our example, we use the PurchaseDate column.)


2 Answers

Both solutions include the last day of the previous month and also include all of "today".

For a date column:

SELECT *
FROM   tbl
WHERE  my_date BETWEEN date_trunc('month', now())::date - 1
               AND     now()::date

You can subtract plain integer values from a date (but not from a timestamp) to subtract days. This is the simplest and fastest way.

For a timestamp column:

SELECT *
FROM   tbl
WHERE  my_timestamp >= date_trunc('month', now()) - interval '1 day'
AND    my_timestamp <  date_trunc('day'  , now()) + interval '1 day'

Note that I use the < operator for the second condition to get precise results (~ "before tomorrow").

I do not cast to date in the second query. Instead I add an interval '1 day', to avoid casting back and forth.

Have a look at date / time types and functions in the manual.

like image 78
Erwin Brandstetter Avatar answered Sep 28 '22 03:09

Erwin Brandstetter


For getting date of previous/last month:

SELECT (date_trunc('month', now())::date - 1) as last_month_date

Result: 2012-11-30

For getting number of days of previous/last month:

SELECT DATE_PART('days', date_trunc('month', now())::date - 1) last_month_days

Result: 30

like image 25
UserBSS1 Avatar answered Sep 28 '22 04:09

UserBSS1