Skip to content

Instantly share code, notes, and snippets.

@adunstan
Created August 7, 2011 17:14
Show Gist options
  • Save adunstan/1130555 to your computer and use it in GitHub Desktop.
Save adunstan/1130555 to your computer and use it in GitHub Desktop.
set all tables clustered by PK if there is one and no clustering index is set
do $$
declare
rec record;
cmd text;
begin
for rec in
select n.nspname, rc.relname as tbl, ic.relname as idx
from pg_index i
join pg_class ic
on i.indexrelid = ic.oid
join pg_class rc
on i.indrelid = rc.oid
join pg_namespace n
on rc.relnamespace = n.oid
where i.indisprimary
and rc.relkind = 'r'
and n.nspname <> 'information_schema'
and n.nspname !~ '^pg_'
and rc.oid not in (select indrelid
from pg_index
where indisclustered)
loop
cmd := 'ALTER TABLE ' || quote_ident(rec.nspname) ||
'.' || quote_ident(rec.tbl) || ' CLUSTER ON ' ||
quote_ident(rec.idx);
-- raise notice 'CMD: %', cmd;
execute cmd;
end loop;
end;
$$;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment