SQL: get number of days until next birthday

What if you have a birthdate and you want to order the records by number of days until the next birthday?

That is what this query does. It takes into account that the birthdate is in the past and you want to get the next birthday given the current date.

SELECT 
  birthday
  , TIMESTAMPDIFF(day, birthday, CURDATE())
  ,365.25 -
        (
          case
            WHEN TIMESTAMPDIFF(day, birthday, CURDATE()) = 0 THEN 364.25
            WHEN birthday IS NULL THEN 0
            ELSE TIMESTAMPDIFF(day, birthday, CURDATE())
          end
          mod 365.25
         ) AS days_till_birthday
FROM users
order by 365.25 -
        (
          case
            WHEN TIMESTAMPDIFF(day, birthday, CURDATE()) = 0 THEN 364.25
            WHEN birthday IS NULL THEN 0
            ELSE TIMESTAMPDIFF(day, birthday, CURDATE())
          end
          mod 365.25
         ) asc

It’s based off of this answer on StackOverflow: https://stackoverflow.com/a/51407757

The difference is that it takes also works for people having their birthday today and ordering the records having NULL values for birthday at the end.

So people without their birthday are places last, where normally the NULL records are ordered first.

Click Here to Leave a Comment Below

Leave a Reply: