-1

I have a users table with a dob (date of birth) field, in a postgres database.

I want to write a query that will retrieve the next five upcoming birthdays. I think the following needs to be considered -

  • Sorting by date of birth won't work because the years can be different.
  • You want the result to be sorted by date/month, but starting from today. So, for example, yesterday's date would be the last row.
  • Ideally, I would like to do this without functions. Not a deal breaker though.

Similar questions have been asked on SO, but most don't even have an accepted answer. Thank you.

Anuj Jain
  • 315
  • 1
  • 15

2 Answers2

3

Well, this got downvoted a lot. But I'll post my answer anyway. One of the answers helped me arrive at the final solution, and that answer has been deleted by its owner for some reason.

Anyway, this query works perfectly. It gives the next 5 upcoming birthdays, along with the dates.

SELECT id, name,
  CASE
    WHEN dob2 < current_date THEN dob2 + interval '1 year'
    ELSE dob2
  END 
  AS birthday
FROM people, 
make_date(extract(year from current_date)::int, extract(month from dob)::int, extract(day from dob)::int) as dob2
WHERE is_active = true
ORDER BY birthday
LIMIT 5;
Anuj Jain
  • 315
  • 1
  • 15
1

You can look at day of year of dob and compare against current date's doy:

SELECT doy
    , extract(doy from dob) - extract(doy from current_date) as upcoming_bday
FROM users
WHERE extract(doy from dob) - extract(doy from current_date) >= 0
order by 2 
limit 5
Jon Ekiz
  • 1,002
  • 6
  • 13