In Postgresql, force unique on combination of two columns

后端 未结 4 2072
故里飘歌
故里飘歌 2020-12-23 00:23

I would like to set up a table in PostgreSQL such that two columns together must be unique. There can be multiple values of either value, so long as there are not two that s

4条回答
  •  粉色の甜心
    2020-12-23 00:45

    If, like me, you landed here with:

    • a pre-existing table,
    • to which you need to add a new column, and
    • also need to add a new unique constraint on the new column as well as an old one, AND
    • be able to undo it all (i.e. write a down migration)

    Here is what worked for me, utilizing one of the above answers and expanding it:

    -- up
    
    ALTER TABLE myoldtable ADD COLUMN newcolumn TEXT;
    ALTER TABLE myoldtable ADD CONSTRAINT myoldtable_oldcolumn_newcolumn_key UNIQUE (oldcolumn, newcolumn);
    
    ---
    
    ALTER TABLE myoldtable DROP CONSTRAINT myoldtable_oldcolumn_newcolumn_key;
    ALTER TABLE myoldtable DROP COLUMN newcolumn;
    
    -- down
    

提交回复
热议问题