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
set to true
.
How can I add this constraint to my column with mysql?
Thanks!
UPDATE
If it is not a constraint that I should add. How are we dealing with this type of problem on DBs?
Check out triggers. They were introduced in version 5.0.2, I believe. You want a "before insert" trigger. If there is already a row with is_default=true, raise an error. I don't know what problems you might with concurrency and so on, but hopefully this is enough to you started.
I don't think it is a problem with the database as much as it is a problem with your model. It is hard for me to come up with a good example of how to solve it since you haven't mentioned what type of data you are representing, but a
XXXType
orXXXConfiguration
table would be able to hold adefaultXXXId
column.Think of it like this: Should the color blue know that it is default or should something else know that the color blue is default when used in a given context?
Changing the way you model your data is often a much better approach to cross-database compatibility than trying to use specific features of one database flavor to represent data in a way that is not necessarily natural to your problem domain if you think about it.
You can't have such a constraint in MySQL.
However if instead of TRUE and FALSE you use the values TRUE and NULL then it will work because a UNIQUE column can have multiple NULL values. Note that this doesn't apply to all databases, but it will work in MySQL.
In some DBMS you can create a partial index.
In PostgreSQL this would look like this:
SQL Server 2008 has a very similar syntax.
On Oracle it's a bit more complicated but doable as well:
The Oracle solution might work on any DBMS that supports expression for an index definition.
Check constraints are not supported in MySQL, this is the solution using trigger:
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.