Skip to content

Instantly share code, notes, and snippets.

@giovannicandido
Last active April 29, 2025 18:15
Show Gist options
  • Save giovannicandido/046a6142eb8872712b948598cc4e01ce to your computer and use it in GitHub Desktop.
Save giovannicandido/046a6142eb8872712b948598cc4e01ce to your computer and use it in GitHub Desktop.
Rename pascal case tables to snake case in postgresql
SELECT ddlsql || regexp_replace(name, E'^_',E'','g') As ddlsql FROM (SELECT 'ALTER TABLE ' || quote_ident(t.table_schema) || '.'
|| quote_ident(t.table_name) || ' RENAME TO ' As ddlsql, quote_ident(lower(regexp_replace(t.table_name, E'([A-Z])', E'\_\\1','g'))) || ';' as name
FROM information_schema.tables As t
WHERE t.table_schema NOT IN('information_schema', 'pg_catalog')
AND t.table_name <> lower(t.table_name)
ORDER BY t.table_schema, t.table_name) x;
@olegyablokov
Copy link

olegyablokov commented Apr 29, 2025

Thank you very much.

Rename "camelCaseColumnNames":

SELECT
  'ALTER TABLE '
  || quote_ident(c.table_schema)
  || '.'
  || quote_ident(c.table_name)
  || ' RENAME COLUMN '
  || quote_ident(c.column_name)
  || ' TO '
  || quote_ident(
       lower(
         regexp_replace(
           regexp_replace(c.column_name, '([A-Z])', '_\1', 'g')
         , '^_', '', 'g')
       )
     )
  || ';'
FROM information_schema.columns AS c
WHERE c.table_schema NOT IN('information_schema','pg_catalog')
  AND c.column_name <> lower(c.column_name)
ORDER BY c.table_schema, c.table_name, c.ordinal_position;

ChatGPT and other LLMs can help in generating similar queries for other cases, including enum types, different cases, etc.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment