Dynamic DDL

From PostgreSQL wiki

Revision as of 12:49, 1 September 2011 by Rhodiumtoad (Talk | contribs)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

Performance Snippets

Dynamic DDL Execution

Works with PostgreSQL


Written in


Depends on


In many examples in this section, an SQL query produces as output a list of DDL statements to be subsequently executed. This is a fairly common administrative requirement.

The following trivial function allows such queries to be executed directly with no intermediate step. Doing this also takes advantage of PostgreSQL's ability to do transactional DDL; either all changes are made, or all are rolled back. Of course, for safety one would typically do an explicit BEGIN; first, and inspect the list of commands and, if necessary, the resulting changes to the database, before doing a COMMIT;.

CREATE FUNCTION exec(text) returns text language plpgsql volatile
  AS $f$
      EXECUTE $1;
      RETURN $1;
Personal tools