Company
Date Published
Author
Franck Pachot
Word count
1104
Language
English
Hacker News points
None

Summary

To generate SQL scripts dynamically using PostgreSQL, you can use several features such as dollar-quoted string constants, format(), and catalog views to get metadata. You can replace outer quotes with $TAG$, build strings dynamically with format(), use %s for text, %L for single-quotes, %I for identifiers that may need double quotes, and %n$ for repeating arguments. Additionally, you can use \gexec to execute the result. The goal is not to execute arbitrary DDL statements in production but to create maintainable scripts free from hardcoded text and double quotes. You should also consider using a small additional where clause when querying from catalog views to create idempotent scripts that avoid executing existing statements again.