How to create a “unique” constraint on a boolean MySQL column?

前端 未结 6 802
遥遥无期
遥遥无期 2020-12-09 08:40

I would like to add a BOOLEAN column to a MySQL table which will be named is_default. In this column, only one record can have is_default

6条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-09 09:33

    How are we dealing with this type of problem on DBs?

    In some DBMS you can create a partial index.

    In PostgreSQL this would look like this:

    CREATE UNIQUE INDEX only_one_true 
      ON the_table (is_default)
      WHERE is_default
    

    SQL Server 2008 has a very similar syntax.

    On Oracle it's a bit more complicated but doable as well:

    CREATE UNIQUE INDEX only_one_true 
      ON the_table (CASE 
                      WHEN is_default = 1 THEN 1
                      ELSE null
                    END)
    

    The Oracle solution might work on any DBMS that supports expression for an index definition.

提交回复
热议问题