Getting the next n birthdays from a table in SQL

If we have a table with a basic structure like this:

----------
person
----------
person_id
name
dob
...
----------

Let’s run a query with the results sorted by order of upcoming birthdays:

SELECT *,
IF(MONTH(`dob`) < MONTH(NOW()) ||
	(MONTH(`dob`) = MONTH(NOW()) && DAY(`dob`) < DAY(NOW())),
	MONTH(`dob`) + 12, MONTH(`dob`)) AS `adjusted_month`
FROM `person`
ORDER BY `adjusted_month`, DAY(`dob`), `name`

An alias called adjusted_month is used.

If the month of birth is earlier then the current month, or if it is the same and the day of birth is earlier then the current day, adjusted_month is set to the the month of birth + 12. Otherwise adjusted_month is just set to the month of birth.

The results can then be sorted by adjusted_month and the day to get the desired result.

Creative Commons License
This work, unless otherwise expressly stated, is licensed under a Creative Commons Attribution-Noncommercial-Share Alike 3.0 License.

Comment (1)

  1. Rafael wrote::

    Thank you, this code just works!

    Sunday, October 11, 2009 at 6:58 am #