MySQL-Query: Howto select upcoming birthdays

In a recent software project I needed to select the upcoming birthdays of the
users. But now I detected a problem with the turn of the year. After some time
of researching and trying, I found a stable solution. For your convenience,
here’s the code:
SET @today = '2007-12-20';
SELECT
user_id,
birthday,
DATE_FORMAT(@today, '%Y') - DATE_FORMAT(birthday, '%Y') + IF(
DATE_FORMAT(birthday, "%m%d") < DATE_FORMAT(@today, "%m%d"), 1, 0) AS new_age,
DATEDIFF(birthday + INTERVAL YEAR(@today) - YEAR(birthday) +
IF(DATE_FORMAT(@today, "%m%d") > DATE_FORMAT(birthday, “%m%d”), 1, 0) YEAR,
@today) AS days_to_birthday
FROM users
HAVING days_to_birthday < 14
ORDER BY days_to_birthday ASC;

And you can easily extend it to limit the result to some specific ages. This is
very useful if you want only the big O coming up:
...
HAVING days_to_birthday < 14 AND new_age IN (10,20,30,40,50,60,70,80,90,100)
...

This entry was posted on Thursday, December 20th, 2007 at 8:14 PM. There are more articles with the same tags: . You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

2 Comments

  1. May 7th, 2009, 12:26 PM by Daniel Sturm

    Hey, thanx for your post! Saved my day ;)


  2. November 25th, 2009, 5:50 PM by Mathias Schreiber

    Lifesaver!


Add Comment




Post Guidelines

Name and email address are required. To prevent spam, your email address will not be displayed.

Line breaks are converted automatically. If you want to add links or apply any formatting, you can use the following tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Spam and irrelevant comments will be deleted, your IP will be banned, and any URLs in your comment will be blacklisted.

top