Let’s say I have a database with several columns.
There is a primary key, Users.
But there is also annother column, Username.
When a new Username is entered into the database, I want to check to make sure it is unique. Since there is already a primary key, maybe I need to put a constraint on Username.
I have no idea how to do this. When I right click on the column name and I bring up “Indexes/Keys” I see “Users_Key” for the existing primary key, not “Users”. So I have to add something like “Username_Keys”? When I do, I don’t see it anywhere in the Object Explorer. But I do see Users_Key under “Keys”?
Is it okay to use a query within SSMS?
Cos then you could do this:
where the table is called
tablenameand the Username column (which you want to be unique) is calledUsername.For multiple columns, do it like this:
To be honest, it’s better to do it the second way, as you may need to drop the constraint later for some reason. Like this:
Don’t forget that a
UNIQUEconstraint has a size limit (I believe it’s around 900 bytes, but not 100% sure), so make sure UserName is not a column type likeNVARCHAR(MAX)or it won’t let you do it! But you’d be insane to let anybody have a username over 100 characters anyway!