Skip to content

Instantly share code, notes, and snippets.

@miguelmota
Last active July 30, 2024 11:59
Show Gist options
  • Save miguelmota/40b8e77982d744b616aed76fd9a5469a to your computer and use it in GitHub Desktop.
Save miguelmota/40b8e77982d744b616aed76fd9a5469a to your computer and use it in GitHub Desktop.
PostgreSQL rename column if not exists
DO $$
BEGIN
IF NOT EXISTS(SELECT *
FROM information_schema.columns
WHERE table_name='my_table' and column_name='my_column')
THEN
ALTER TABLE "public"."my_table" RENAME COLUMN "my_column" TO "my_new_column";
END IF;
END $$;
@wdebeau1
Copy link

wdebeau1 commented Jan 18, 2019

This looks backwards. Shouldn't it either be
"IF EXISTS"
or
change column_name='my_column' to column_name='my_new_column'
?

Other than that, this was quite helpful, thanks :)

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