1

I want to add a new user in my table users

users
------
ID  NAME
1   abc
2   cde

how could I use the syntax 'no exists' in this case if for example someone by mistake insert another user with the name 'abc' I dont want to enter with the same name user again.

Ronald
  • 159
  • 11
  • If your names should be `UNIQUE` then put a unique constraint on the column. This will then ensure that someone cannot enter a duplicate value in that column. – T I Jun 12 '13 at 06:50
  • In this case it would be better to use a unique constraint on the `NAME` field. – STLDev Jun 12 '13 at 06:51
  • 1
    Probably this is what you want: http://stackoverflow.com/questions/5288283/sql-server-insert-if-not-exists-best-practice – Sqeezer Jun 12 '13 at 06:52
  • You can Make Name field UNIQUE, but when you are inserting records, call inserting function in try/catch block. because if user insert same Name it will through an Exception.. @Ronald Andrade – PSK Jun 12 '13 at 06:55
  • My table which has 10-15 million rows. If I put a unique constraint on 3-4 columns, will this be a problem ? Thanks. – Steam Feb 19 '14 at 01:53

1 Answers1

0

You just need to make the column as UNIQUE

ALTER IGNORE TABLE users ADD UNIQUE (NAME);

This will prevent to have duplicates in the column NAME

Fabio
  • 21,516
  • 12
  • 49
  • 63