views:

89

answers:

1

I have problem with unique rows in db table, now it is posible to do that:

id  | Name  | LastName  | City
-------------------------------------
1   | John  | Moore     | London
2   | John  | Moore     | London

when i use UNIQUE attribute in all columns i have errors inserting second Moore even it is different Name :/

how use UNIQUE (or maybe INDEX?) to do something like that in my table in db:

id  | Name  | LastName  | City
-------------------------------------
1   | John  | Moore     | London
2   | Jake  | Moore     | London
3   | John  | Keen      | London
4   | John  | Moore     | London //but good error when inserting the same row

Sorry if question is easy, but i am beginner at sql, and have problems with find some good example with using a UNIQUE like a want:/ or maybe I must just before inserting a new row selecting a table from db and check if it exist?

+9  A: 

Remove the unique index on the individual column and make it on both columns together, like this:

CREATE UNIQUE INDEX ixFullName ON yourTable (LastName, Name);
Rob Farley
I was about to suggest a unique constraint - after seeing your answer I did some digging and found this interesting article on the difference between unique index and unique constraint http://msdn.microsoft.com/en-us/library/aa224827(SQL.80).aspx
David Hall
Thanks David. I certainly consider them identical, and prefer to think of them as indexes because of the fact that they can be used in an Index Seek/Scan operator.
Rob Farley
A unique index can also have INCLUDE columns. A constraint can not.
gbn
True... but I was more thinking "What does a constraint give you that an index doesn't", since many people say "You should use a constraint, not an index"
Rob Farley
I think it's more about how you're using it. If you are creating the constraint to prevent duplicates / enforce uniqueness, then you should think about it as a constraint. If you are creating the index to improve performance, then you should think about it as an index.
Aaron Bertrand
I want use UNIQUE in first option. Its better for me that db don't let insert duplicates than write in all asp.net class function to select all table and looking for duplicates. Its better performance,don't You think ? ;)
netmajor
@netmajor - Yes. Use a Unique Constraint/Index to make sure that the uniqueness is maintained for you.
Rob Farley
@Aaron - Yeah, that's valid. I just end up doing it with an index these days, and have started referring to them as indexes generally. I think it comes down to the fact that I look at indexes as providing lots of information to the QO now.
Rob Farley