I am currently developing an architecture in PHP and MySQL and a problem has arisen. I hope this isn’t a ridiculous question but it would be very helpful if there was an answer.
The following is a simplified version of the actual situation. Lets say I have a table with 3 columns representing a number of locations. Each location can potentially be a default location:
location_id int(20), location_name varchar(255), is_default BOOL
Column is_default should only have the values true (1) or false (0). In addition I want to make sure that no more than one row can have is_default set to true. In other words I want to permit a maximum of one true value and a boundless amount of false values:
+-------------+---------------+------------+
| location_id | location_name | is_default |
+-------------+---------------+------------+
|1 |'England' |1 |
|2 |'America' |0 |
|3 |'China' |0 |
|4 |'Russia' |0 |
+-------------+---------------+------------+
The idea is that only one location can be the default location. Is there any way of expressing this as a data type or column attribute of some sort? Or would I have to enforce the rule in php by simply running two queries so that whenever a location is added whose is_default column = true the old default location’s is_default column = false? It would be great if there was a way to enforce it in MySQL.
It seems like such a simple problem that I thought it would be common but I can’t seem to find an answer anywhere on the internet including the MySQL reference. Unless there is some obvious database design flaw which I have managed to overlook.
If you don’t have another table where it belongs, I would create a separate table to specify the default like:
This way, you can only have one.
Maybe this belongs in a settings table?