Upcoming Birthdays Across Year Boundary

Rank upcoming birthdays with a modulo month cycle so December and January sit adjacent instead of being split by the calendar year.

SqlData Fetching

Code

snippet
-- upcoming birthdays wrap across the year boundary: December sorts next to January
CREATE TABLE birthdays (
    person_id int PRIMARY KEY,
    name      text NOT NULL,
    born_on   date NOT NULL
);

INSERT INTO birthdays VALUES
    (1, 'ada', DATE '1990-12-28'),
    (2, 'raj', DATE '1985-01-03'),
    (3, 'lin', DATE '1992-06-11'),
    (4, 'kim', DATE '1988-11-30');

-- cyclic month order anchored at the current month: December sits one step from January and never splits across the year boundary
SELECT
    person_id,
    name,
    born_on,
    EXTRACT(MONTH FROM born_on) AS birth_month,
    EXTRACT(DAY FROM born_on)   AS birth_day,
    ((EXTRACT(MONTH FROM born_on)::int - EXTRACT(MONTH FROM CURRENT_DATE)::int) + 12) % 12
        AS months_until
FROM birthdays
ORDER BY months_until, birth_day;

What the code does

What runs here is SELECT / INSERT / CREATE — birthdays, born_on and current_date are the objects involved.

What the statements actually assemble: an ORDER BY that fixes the output order; NOT NULL qualifiers on the required columns; a PRIMARY KEY that enforces row identity.

Applying it

The birthdays table is the working surface here.

Statements that matter

SELECT
    person_id,
    name,
    born_on,
    EXTRACT(MONTH FROM born_on) AS birth_month,
    EXTRACT(DAY FROM born_on)   AS birth_day,
    ((EXTRACT(MONTH FROM born_on)::int - EXTRACT(MONTH FROM CURRENT_DATE)::int) + 12) % 12
        AS months_until
FROM birthdays
ORDER BY months_until, birth_day;
INSERT INTO birthdays VALUES
    (1, 'ada', DATE '1990-12-28'),
    (2, 'raj', DATE '1985-01-03'),
    (3, 'lin', DATE '1992-06-11'),
    (4, 'kim', DATE '1988-11-30');
CREATE TABLE birthdays (
    person_id int PRIMARY KEY,
    name      text NOT NULL,
    born_on   date NOT NULL
);

Interactive Tools for This Topic

FAQ

Which tables appear in this script?
The references are `birthdays`, `born_on`, `current_date`.