Imagine we have a table of countries, and a table of cities. A country can of course have many cities, but a city can only be in one country, thus a one-to-many relationship makes intuitive sense:
countries
| id | name |
| 1 | Lorwick |
| 2 | Belmead |
cities
| id | country | name |
| 1 | 1 | Marblecrest |
| 2 | 1 | Westacre |
| 3 | 2 | Belcoast |
| 4 | 1 | Rosemarsh |
| 5 | 2 | Vertston |
But in addition to our one-to-many relationship, we want to describe the one-to-one relationship of national capitals. If it matters, assume that capitals may change fairly regularly, and for that matter cities appear and vanish at will, and that cities may switch countries. Point is, this data is unstable.
I see a couple of options:
Add an int column
capital
tocountries
which cannot be null. Pro: always exactly one city; Con: not associated with the city, nothing enforcing the city is in the country, or that it even exists.Add a boolean column
capital
tocities
, which if true indicates the city is the capital of the associated country. Pro: directly associated with the city in question, no duplicate columns indicating hierarchy; Con: pretty sure this is poor normalization as there's nothing stopping there being zero, or more than one, "capital" for a given country.Create an additional table
capitals
with columnscountry
andcity
and a unique constraint on both columns (or at least oncity
). Pro: feels cleaner, easy joining on eithercountries
orcities
; Con: still doesn't ensure city is in country, or that either exist.
What is the most normalized and/or best way to represent this relationship? Is there any way to ensure each country has exactly one capital which does in fact exist and resides inside that country? I imagine it's not possible, in which case, how can I best minimize issues for my client code?
I'm currently using SQLite, but I'm interested in generalized answers, regardless of the underlying database.
I did a little digging and found Indicating primary/default record in database but I don't think this really answers my question.
PS: It's not that bad if there's no capital (there may be no cities!), but it would be bad if there were multiple.