How to create a single index based on two columns?

Asked

Viewed 1,716 times

4

I have a table with these columns:

ip
nome
email

I want you to ip and the email are a single pair. The same ip may contain several records and a single email may also. But the same ip and even email must be unique.

So that, this would be possible:

  - ip              nome              email
1 - 187.89.98.4     João              [email protected]  // ip repetido com registro 2
2 - 187.89.98.4     Maria             [email protected] // ip repetido com registro 1; email repetido com registro 3
3 - 197.19.1.47     Vinicius          [email protected] // e-mail repetido com registro 2

But this is not:

  - ip              nome              email
1 - 187.89.98.4     João              [email protected] // mesmo ip com mesmo e-mail com registro 2
2 - 187.89.98.4     Maria             [email protected] // mesmo ip com mesmo e-mail com registro 1

because I don’t want you to ip and email repeat.

1 answer

5


CREATE UNIQUE INDEX IpEmail ON tabela (ip ASC, email ASC)

Documentation.

I hope you have another column that is primary, these data may vary and are not good candidates for primary key. If you want to insist:

ALTER TABLE tabela ADD CONSTRAINT IpEmail PRIMARY KEY CLUSTERED (ip, email);

Documentation.

I put in the Github for future reference.

  • What are good primary key candidates? In shallow examples, not clinging to the context of my question.

  • 2

    I think this is another question and I may have already answered: https://answall.com/search?q=user%3A101+key+Prim%C3%A1ria

Browser other questions tagged

You are not signed in. Login or sign up in order to post.