In PostgreSQL, I am attempting to fetch the previous Thursday and the previous Wednesday based on a thursday date (for example 2024-01-18). I have tried the following queries:
For the previous Thursday:
SELECT
date_trunc('week', '2024-01-18'::date) - INTERVAL '5 days' AS previous_wednesday, -- not working
date_trunc('week', '2024-01-18'::date) - INTERVAL '4 days' AS previous_thursday;
db fidle: https://www.db-fiddle.com/f/9GFNcJ81QfspGezYxhMib1/0
Which gives me
previous_wednesday | previous_thursday |
---|---|
2024-01-10T00:00:00.000Z | 2024-01-11T00:00:00.000Z |
Expected result :
previous_wednesday | previous_thursday |
---|---|
2024-01-17T00:00:00.000Z | 2024-01-11T00:00:00.000Z |
I would like assistance to find the desired result.
2
Answers
If the given date is always a thursday:
No need for date_trunc, which would set the date to the start of the given week before adding/subtracting the interval.
If the given date isn’t always a thursday, you may want to use date_trunc to start your calulcation always from monday of the given date.
The
extract()
function can give you thenumeric
day of the week. You can use it in acase
statement to move back accordingly, or combine with modulo%
operator: demo