I have a books table with a returned_date column. I'd like to see the results for all of the books with a returned date that occurred in the past week.
Any thoughts? I tried doing some date math, but Postgres wasn't happy with my attempt.
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()::dateis the Postgres implementation of standard SQLCURRENT_DATE. Both do exactly the same in PostgreSQL.CURRENT_DATE - 7works because one can subtract / addintegervalues (= days) from / to adate. An unquoted number like7is a numeric literal defaulting tointegerwhile it only contains digits and an optional leading sign, so an explicit cast is not necessary.With data type
timestamportimestamptzyou have to add / subtract aninterval, like @Eric demonstrates. You can do the same withdate, but the result istimestampand you have to cast back todateor keep working withtimestamp. Sticking todatelike 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 - 7or>= current_date - 6. To exclude today make it
BETWEEN current_date - 7 AND current_date - 1(or similar).>= current_date - 7as 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
- To include today make it
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
来源:https://stackoverflow.com/questions/8732517/how-do-you-find-results-that-occurred-in-the-past-week