In Postgresql, force unique on combination of two columns

后端 未结 4 2069
故里飘歌
故里飘歌 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:35

    Create unique constraint that two numbers together CANNOT together be repeated:

    ALTER TABLE someTable
    ADD UNIQUE (col1, col2)
    
    0 讨论(0)
  • 2020-12-23 00:37
    CREATE TABLE someTable (
        id serial primary key,
        col1 int NOT NULL,
        col2 int NOT NULL,
        unique (col1, col2)
    )
    

    autoincrement is not postgresql. You want a serial.

    If col1 and col2 make a unique and can't be null then they make a good primary key:

    CREATE TABLE someTable (
        col1 int NOT NULL,
        col2 int NOT NULL,
        primary key (col1, col2)
    )
    
    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2020-12-23 00:51

    Seems like regular UNIQUE CONSTRAINT :)

    CREATE TABLE example (
    a integer,
    b integer,
    c integer,
    UNIQUE (a, c));
    

    More here

    0 讨论(0)
提交回复
热议问题