Skip to content

Instantly share code, notes, and snippets.

@zachvictor
Created January 29, 2021 02:42
Show Gist options
  • Save zachvictor/7cf3168eef465330695f6caadebbc2ec to your computer and use it in GitHub Desktop.
Save zachvictor/7cf3168eef465330695f6caadebbc2ec to your computer and use it in GitHub Desktop.
PostgreSQL query to generate a calendar
-- Generate a calendar in PostgreSQL
-- Rather than create a calendar table and insert rows into it statically,
-- this approach materializes a recursive [iterative] query.
CREATE MATERIALIZED VIEW cal AS
WITH RECURSIVE dd(d) AS (
VALUES ('2005-01-01'::DATE)
UNION ALL
SELECT d + 1
FROM dd
WHERE d < '2025-01-01'::DATE
)
SELECT d dt
, to_char(d, 'dy') dy
, to_char(d, 'D') daynum
, to_char(d, 'ID') isodaynum
, to_char(d, 'YYYY')::INT y
, to_char(d, 'IYYY')::INT iy
, to_char(d, 'YYYYWW')::INT yw
, to_char(d, 'IYYYIW')::INT iyw
, to_char(d, 'YYYYMM')::INT ym
, to_char(d, 'YYYYQ')::INT yq
, to_char(d, 'YYYY-WW') y_w
, to_char(d, 'IYYY-IW') iy_w
, to_char(d, 'YYYY-MM') y_m
, to_char(d, 'YYYY"Q"Q') y_q
FROM dd
;
-- Change whatever you like. This calendar starts on 2005-01-01
-- and ends 2024-12-31 and includes date expressions for convenience,
-- some in both numeric and char types. Search "Data Type Formatting
-- Functions" in the PostgreSQL documentation for more info.
-- Go see cal, go see cal, go see cal.
-- https://en.wikipedia.org/wiki/Cal_Worthington
-- https://www.youtube.com/watch?v=0HJALwCNbco
-- https://genius.com/Cal-worthington-go-see-cal-lyrics
-- https://www.scpr.org/news/2013/09/09/39147/cal-worthington-car-dealer-famous-for-go-see-cal-a/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment