Tag Archives: birthdays

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 [...]