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.
Code
-- 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
SQL DDL to TypeScript ConverterConvert SQL CREATE TABLE DDL statements into strict TypeScript interfaces with nullable, array, enum, JSONB, and Date or ISO string column mappings.PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.Age CalculatorCalculate exact age in years, months, and days between a birth date and a reference date, plus total days and the next birthday countdown.Business Days CalculatorCount the weekdays between two dates, excluding weekends and any holidays you list, and see how many calendar and weekend days are involved.
FAQ
- Which tables appear in this script?
- The references are `birthdays`, `born_on`, `current_date`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.