How to drop column if it exists in PostgreSQL 9+?

SqlPostgresql

Sql Problem Overview


I am trying to drop a column from a table. How can I check if the column exists or not?

I went through the documentation at https://www.postgresql.org/docs/9.2/static/sql-altertable.html, but didn't find any example how to do it.

Even found https://stackoverflow.com/questions/133031/how-to-check-if-a-column-exists-in-sql-server-table, but it does not seem relevant.

Sql Solutions


Solution 1 - Sql

You just need to add IF EXIST to your DROP COLUMN statement:

ALTER TABLE tableName
DROP COLUMN IF EXISTS columnName;

Solution 2 - Sql

You can also try via IF EXISTS Method which work great while we are using migration

DO $$

BEGIN

	IF EXISTS(
	SELECT column_name FROM information_schema.columns WHERE table_name = tableName AND column_name = columnName)
	THEN
		ALTER TABLE tableName DROP COLUMN columnName;
	END IF;

END $$;

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser3521432View Question on Stackoverflow
Solution 1 - Sqluser3521432View Answer on Stackoverflow
Solution 2 - SqlPiyush SharmaView Answer on Stackoverflow