Based on Constraint for only one record marked as default would the same approach of a view and unique clustered index apply if I wanted to achieve the same result at a table scope?
I have a table called Accounts. There can be only one System account, however there can be many Partner and Client accounts. Each type of account does not vary in terms of the columns but instead with just the Type column.
ID | Type | Name
1 System Contoso
2 Partner Wingtip
3 Partner Northwind
4 Client Adventure Works
5 Client Fabrikam
In the above I want to prevent adding another System account, but allow many partner and client accounts. It feels like a concern that belongs in the database as opposed to the domain (maybe I’m wrong)?
If you know that the system account will always have ID number 1, you can implement this with a CHECK constraint. Something along these lines . . .
In fact, if this is your database, the system account can have any id number. Just change the CHECK() constraint to match.
If you’re building for deployment to a client site, you can add the system account before deployment. (And you probably should, regardless of how you handle the constraints.)
Think about about what to do when a user tries to delete rows from this table. (Especially that system account row.) Then think about what to do when a database admin tries to delete rows from that table.
You can probably use a foreign key constraint (no cascade) or a trigger to prevent a database admin from accidentally deleting the system account. The admin can probably get around those restrictions, but you’d hope she knows what she’s doing if she’s willing to go that far to delete a row.