unique constraint against 2 columns?

  • i know this can be done, but don't know how so figure i would

    just ask.

    if i have 2 columns... firstname & lastname

    i want to make sure that both columns contain a unique name, but

    obviously i can't make a 'unique' constraint per column cause it's

    not uncommon to find more than one 'chris', or 'smith'. so how do

    i make a UNIQUE constraint against the combination of names?

    not sure the lingo for such a constraint. is it simply called a

    "2 column constraint"

    thoughts?

    _________________________

  • Well you are likely to get more than one "Chris Smith" as well as more than one "Chris" and more than one "Smith".

    ALTER TABLE dbo.MyTable

    ADD CONSTRAINT unq_MyTable UNIQUE (FirstName,LastName)

  • First of all, are you sure that all of your firstname/lastname combinations will be unique?  There are plenty of Bob Smith's in the world (no offense meant to any of the Bobs!). 

    Assuming that all of your firstname/lastname combinations will be unique, why not make firstname, lastname a non-clustered Primary Key for your table.  Primary Keys are always unique.  This will allow you to have multiple Bobs, multiple Smiths, but only one Bob Smith.

    John Rowan

    ======================================================
    ======================================================
    Forum Etiquette: How to post data/code on a forum to get the best help[/url] - by Jeff Moden

  • yeah i know... i was just using the 'chris' & 'smith' as an example.

    just learning the basics here, and thought i would throw that out ther.

    question is... is there a term for making a constraint operate against

    two columns?

    _________________________

  • Both ways demonstraited here would work.  If your 2 columns should logically be part of a composit key, use the Primary Key method.  If you just need a unique constraint accross 2 columns, use the constraint method shown.

    John Rowan

    ======================================================
    ======================================================
    Forum Etiquette: How to post data/code on a forum to get the best help[/url] - by Jeff Moden

Viewing 5 posts - 1 through 4 (of 4 total)

You must be logged in to reply to this topic. Login to reply