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

前端 未结 2 1536
难免孤独
难免孤独 2021-01-03 17:13

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/stati

相关标签:
2条回答
  • 2021-01-03 17:51

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

    ALTER TABLE tableName
    DROP COLUMN IF EXISTS columnName;
    
    0 讨论(0)
  • 2021-01-03 18:08

    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 $$;
    
    0 讨论(0)
提交回复
热议问题