r/DatabaseHelp • u/Hanxarin • Feb 21 '16
SQL Table Having Composite Key but..
I need help to find a way around something. I have an SQL table which contains some fields, two of which being username (text) and deleted (true/false). I was wondering if it is possible to create a restriction where there cannot be a two of the same usernames with deleted false.
This means that multiple entries may have the same username given that only one of them has deleted set to false.
How may i specify this when creating the table? Thank you.
2
Upvotes
2
u/wolf2600 Feb 21 '16
I can't think of a way to configure the table to check for this. Probably be best to implement the logic in the application layer when an insert is performed.
2
u/Grundy9999 Feb 21 '16
I don't have any experience with SQL server, but in Access, after deduplicating the existing table, I would then concatenate the two fields, then make that concatenated field the primary key of the table. Any future attempts to append the table with a record with the same composite primary key value would be rejected as a key violation, while the other records would with no key violation would append. I don't know if the behavior in SQL server is the same, but you may want to investigate that possibility.
1
u/alinroc Feb 22 '16
Allowing non-unique usernames is a bad idea in the first place - how do you distinguish between them? Why do you have to accommodate this?