sqlmysqlconstraints

How to create a "unique" constraint on a boolean MySQL column?


I would like to add a BOOLEAN column to a MySQL table which will be named is_default.

How can I constrain this column so only one record can have is_default set to true?


Solution

  • I think this is not the best way to model the situation of a single default value.

    Instead, I would leave the IsDefault column out and create a separate table with one row and only the column(s) that make(s) up the primary key of your main table. In this table you place the PK value(s) that identify the default record.

    This results in considerably less storage and avoids the update issue of temporarily not having a default value (or, alternatively, temporarily having two default values) when you update.

    You have numerous options for ensuring that there is one-and-only-one row in the default table.