102

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 How to check if a column exists in a SQL Server table?, but it does not seem relevant.

1
  • The information schema query in the question you link to should work in PostgreSQL. Commented Nov 7, 2016 at 21:02

2 Answers 2

178

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

ALTER TABLE tableName
DROP COLUMN IF EXISTS columnName;
Sign up to request clarification or add additional context in comments.

Comments

6

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 $$;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.