Most Recent Week Day

Recently I was reviewing someone’s code for a function in PostgreSQL and I saw a block that was supposed to calculate the most recent Friday of the week. After working on improving it I came up with the following queries that will show the most recent Monday through Sunday when run in PostgreSQL:

The most recent of a day means that if today is the day of the week that we are looking for today’s date will be shown, otherwise it will be a date before today. The above queries can of course be changed to pull the most recent day of the week based on a field by replacing CURRENT_DATE with the date that you want to base off of.

Previous Week Day

Working off of this same train of thought I figured it would be nice to have a query that will show the last Monday through last Sunday that occurred instead of the most recent since the most recent could be today. The following queries show the last previous week days from Monday to Sunday:

The above queries differ from the most recent day of the week queries because it will never give today as a previous day of the week. Again the above queries can of course be changed to pull the most recent day of the week based on a field by replacing CURRENT_DATE with the date that you want to base off of.

Happy querying! šŸ˜Ž

Categories: BlogSQL

Leave a Reply

Your email address will not be published. Required fields are marked *