Skip to content

Instantly share code, notes, and snippets.

@tsnobip
Last active May 10, 2021 11:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tsnobip/831be3690a6282fc2fb8f77e23edcd91 to your computer and use it in GitHub Desktop.
Save tsnobip/831be3690a6282fc2fb8f77e23edcd91 to your computer and use it in GitHub Desktop.
Postgres: Rename column if exists
CREATE OR REPLACE FUNCTION column_exists(
pschema TEXT,
ptable TEXT,
pcolumn TEXT)
RETURNS BOOLEAN AS $BODY$
-- does the requested table.column exist in schema?
SELECT EXISTS
( SELECT NULL
FROM information_schema.columns
WHERE table_name=ptable
AND column_name=pcolumn
AND table_schema=pschema
);
$BODY$
LANGUAGE SQL stable strict;
CREATE OR REPLACE FUNCTION rename_column_if_exists(
pschema TEXT,
ptable TEXT,
pcolumn TEXT,
new_name TEXT)
RETURNS VOID AS $BODY$
BEGIN
-- Rename the column if it exists.
IF column_exists(pschema, ptable, pcolumn) THEN
EXECUTE FORMAT('ALTER TABLE %I.%I RENAME COLUMN %I TO %I;',
pschema, ptable, pcolumn, new_name);
END IF;
END$BODY$
LANGUAGE plpgsql VOLATILE;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment