Skip to content

Instantly share code, notes, and snippets.

@jdbranham
Created March 31, 2022 22:42
Show Gist options
  • Select an option

  • Save jdbranham/17cabeb8fb65bb3f4215e07f898132b0 to your computer and use it in GitHub Desktop.

Select an option

Save jdbranham/17cabeb8fb65bb3f4215e07f898132b0 to your computer and use it in GitHub Desktop.
Postgres Queries
-- create a table ready for partitions
CREATE TABLE IF NOT EXISTS public.mytable (
dob date NULL
--other columns...
) PARTITION BY RANGE (dob)
WITH (
OIDS = FALSE
);
-- create a yearly and monthly sequence of partitions
DO $$
BEGIN
FOR i IN 2019..2023
loop
FOR j IN 1..11
LOOP
EXECUTE format('create table %I partition of public.mytable for values FROM (''%s-%s-01'') to (''%s-%s-01'')', 'public.mytable_y' || i || '_m' || to_char(j, 'FM00'), i, to_char(j, 'FM00'), i, to_char(j+1, 'FM00'));
END loop;
EXECUTE format('create table %I partition of public.mytable for values FROM (''%s-12-01'') to (''%s-01-01'')', 'public.mytable_y' || i || '_m12', i, i+1);
END LOOP;
END;
$$;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment