// SQL snippet

Find the next anniversary of a date in SQL

Renewal emails and anniversary bonuses need the next occurrence of a stored date, which may be this year or next.

Main statement
SQL Server
Também cobre
PostgreSQL

The task

Take the hire month and day, place it in the current year, and push to next year if that date already passed.

The snippet

Written for SQL Server. Versions for PostgreSQL are under Variations.

SQL Server
SELECT
    hire_date,
    DATEADD(YEAR,
        DATEDIFF(YEAR, hire_date, GETDATE())
          + CASE WHEN DATEADD(YEAR, DATEDIFF(YEAR, hire_date, GETDATE()), hire_date) < CAST(GETDATE() AS DATE)
                 THEN 1 ELSE 0 END,
        hire_date) AS next_anniversary
FROM employees;

Como funciona

DATEDIFF(YEAR, ...) counts calendar-year boundaries, so DATEADD(YEAR, that count, hire_date) is this year's anniversary; the CASE adds one more year when it has already passed. Building the date with DATEADD rather than DATEFROMPARTS(YEAR(GETDATE()), MONTH(hire_date), DAY(hire_date)) matters for Feb 29 hires: DATEADD maps them to Feb 28 in non-leap years, while DATEFROMPARTS raises an error. Today's anniversary counts as the next one.

Variations

PostgreSQL

PostgreSQL
SELECT
    hire_date,
    hire_date + interval '1 year'
        * (EXTRACT(YEAR FROM age(CURRENT_DATE, hire_date))::int
           + CASE WHEN (hire_date + interval '1 year'
                        * EXTRACT(YEAR FROM age(CURRENT_DATE, hire_date))::int) < CURRENT_DATE
                  THEN 1 ELSE 0 END) AS next_anniversary
FROM employees;

Questions that come up

Can I order by upcoming anniversaries?

Yes: ORDER BY next_anniversary works as written since every value is today or later. For a 'next 30 days' list, filter on the computed value (wrap the query in a CTE), not on the raw hire_date.

Keep reading

// snippets are better with a schema brain

Run these with autocomplete that knows your tables

SQLly is a native SQL workbench for macOS, Windows and Linux. Paste a snippet into a live connection and you get schema-aware IntelliSense, a plan viewer and guards against unsafe edits.