Problem:
You want to select dates that have an anniversary within the next 14 days, but you want to do this by excluding the year.
Example Query:
SELECT * FROM events WHERE EXTRACT(month FROM "date") = 3 AND EXTRACT(day FROM "date") < EXTRACT(day FROM "date") + 14;
Challenge:
The above query doesn't work because it doesn't account for the wrap-around effect of months.
Solutions:
1. Advanced Version
This solution uses a custom SQL function and a multicolumn index for optimal performance.
CREATE OR REPLACE FUNCTION f_mmdd(date) RETURNS int LANGUAGE sql IMMUTABLE PARALLEL SAFE STRICT AS 'SELECT EXTRACT(month FROM )::int * 100 + EXTRACT(day FROM )::int'; CREATE INDEX event_mmdd_event_date_idx ON event(f_mmdd(event_date), event_date); SELECT * FROM event e WHERE f_mmdd(e.event_date) BETWEEN f_mmdd(current_date) AND f_mmdd(current_date + 14);
2. Table Function
This solution uses a PostgreSQL table function to handle the anniversary calculation.
CREATE OR REPLACE FUNCTION f_anniversary(_the_date date = current_date, _days int = 14) RETURNS SETOF event LANGUAGE plpgsql AS $func$ DECLARE d int := f_mmdd(); d1 int := f_mmdd( + - 1); -- fix off-by-1 from upper bound BEGIN IF d1 > d THEN RETURN QUERY SELECT * FROM event e WHERE f_mmdd(e.event_date) BETWEEN d AND d1 ORDER BY f_mmdd(e.event_date), e.event_date; ELSE -- wrap around end of year RETURN QUERY SELECT * FROM event e WHERE f_mmdd(e.event_date) >= d OR f_mmdd(e.event_date) <= d1 ORDER BY (f_mmdd(e.event_date) >= d) DESC, f_mmdd(e.event_date), event_date; -- chronological across turn of the year END IF; END $func$; SELECT * FROM f_anniversary();
The above is the detailed content of How to Calculate Dates Ignoring the Year in SQL?. For more information, please follow other related articles on the PHP Chinese website!