I work with a Postgres database. This DB has a table with users, who have a birthdate (date field). Now I want to get all users who have their birthday in the upcoming week.
I'm not overly confident in this, but it seems to work in my testing. The key here is the OVERLAPS
operator, and some date arithmetic.
I assume you have a table:
create temporary table birthdays (name varchar, bday date);
Then I put some stuff into it:
insert into birthdays (name, bday) values
('Aug 24', '1981-08-24'), ('Aug 04', '1982-08-04'), ('Oct 10', '1980-10-10');
This query will give me the people with birthdays in the next week:
select * from
(select *, bday + date_trunc('year', age(bday)) + interval '1 year' as anniversary from birthdays) bd
where
(current_date, current_date + interval '1 week') overlaps (anniversary, anniversary)
The date_trunc
truncates the date at the year, so it should get you up to the current year. I wound up having to add one year. This suggests to me I have an off-by-one in there for some reason. Perhaps I just need to find a way to get dates to round up. In any case, there are other ways to do this calculation. age
gives you the interval from the date or timestamp to today. I'm trying to add the years between the birthday and today to get a date in the current year.
The real key is using overlaps
to find records whose dates overlap. I use the anniversary date twice to get a point-in-time.