How do you find results that occurred in the past week?

时光毁灭记忆、已成空白 提交于 2019-11-30 03:06:54
Eric

You want to use interval and current_date:

select * from books where returned_date > current_date - interval '7 days'

This would return data from the past week including today.

Here's more on working with dates in Postgres.

Assuming returned_date is actually data type date, this is simpler, faster and correct:

SELECT * FROM books WHERE returned_date > CURRENT_DATE - 7
  • now()::date is the Postgres implementation of standard SQL CURRENT_DATE . Both do exactly the same in PostgreSQL.

  • CURRENT_DATE - 7 works because one can subtract / add integer values (= days) from / to a date. An unquoted number like 7 is a numeric literal defaulting to integer while it only contains digits and an optional leading sign, so an explicit cast is not necessary.

  • With data type timestamp or timestamptz you have to add / subtract an interval, like @Eric demonstrates. You can do the same with date, but the result is timestamp and you have to cast back to date or keep working with timestamp. Sticking to date like demonstrated is the simplest and fastest possible way. Performance difference is typically small, though.

  • The computation is independent from the actual data type of returned_date, the resulting type to the right of the operator will be coerced to match either way (and raise an error if no cast is registered).

  • For the "past week":

    • To include today make it > current_date - 7 or >= current_date - 6.
    • To exclude today make it BETWEEN current_date - 7 AND current_date - 1 (or similar). >= current_date - 7 as other answers suggest returns rows for the last 8 days instead of 7 and is wrong, strictly speaking.

    • To get the last full calendar week, ending with Sunday, excluding today:
      BETWEEN date_trunc('week', now())::date - 7 AND date_trunc('week', now())::date - 1

Note that the exact definition of "day" and "week" always depends on your current timezone setting.

What math did you try?

This should work

select * from books where current_date - integer '7'

Taken from PostgreSQL Date/Time Functions and Operators

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!