Ashish CMazee
Ashish CMazee

Reputation: 11

Finding the last date of the previous quarter from current date in PostgreSQL

For example: If my current date is 2022-07-21, my query should give me 2022-06-30. I could easily do it in IBM DB2 but struggling in postgresql.

Upvotes: 0

Views: 1194

Answers (1)

Marth
Marth

Reputation: 24812

You can truncate the current date to its quarter, then remove 1 day from that (and potentially cast back to date):

-- You really only need the last column, the other two just show the different steps in the process
SELECT DATE_TRUNC('quarter', CURRENT_DATE)
     , DATE_TRUNC('quarter', CURRENT_DATE) - '1 day'::INTERVAL
     , (DATE_TRUNC('quarter', CURRENT_DATE) - '1 day'::INTERVAL)::DATE

outputs

+---------------------------------+---------------------------------+----------+
|date_trunc                       |?column?                         |date      |
+---------------------------------+---------------------------------+----------+
|2022-07-01 00:00:00.000000 +00:00|2022-06-30 00:00:00.000000 +00:00|2022-06-30|
+---------------------------------+---------------------------------+----------+

Upvotes: 2

Related Questions