Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Unique key insertions

I have a Users table, which has a Unique constraint on the username (for obvious reasons).

I am using an EF 4.0 DAL to populate the database, and in the process of coding the CreateUser() method.

Is it...

  1. Best to catch the SqlException thrown if I try to insert a username which already exist.
  2. Explicitly check for the username before I try to insert it to the database?

If you could also give reasons as to why, that would be great!

like image 913
Darbio Avatar asked Nov 05 '10 03:11

Darbio


People also ask

How do you insert unique rows in SQL?

INSERT DISTINCT Records INTO New Tables In order to copy data from an existing table to a new one, you can use the "INSERT INTO SELECT DISTINCT" pattern. After "INSERT INTO", you specify the target table's name - organizations in the below case.

How do I create a unique key constraint in SQL?

The syntax for creating a unique constraint using an ALTER TABLE statement in SQL Server is: ALTER TABLE table_name ADD CONSTRAINT constraint_name UNIQUE (column1, column2, ... column_n); table_name.

Can we have multiple unique keys in SQL?

A table can have more than one unique key unlike primary key. Unique key constraints can accept only one NULL value for column. Unique constraints are also referenced by the foreign key of another table.

Can a table have 2 unique keys?

Yes a table can have n number of unique and foreign keys. Unique key constraints are used to ensure that data is not duplicated in two rows in the database. One row in the database is allowed to have null for the value of the unique key constraint.


1 Answers

I would check if the record exists first. Unique key constraints are useful to guard against possible ways your application is allowing "bad" data through in the first place, but not the main stop for that. It's generally a bad idea to use exceptions as a control flow mechanism (validation in this case) when it's possible to avoid.

EDIT: To avoid confusion, I'm not saying don't have the unique index at all. It should be there, but it shouldn't be the primary means of checking for uniqueness.

like image 174
vcsjones Avatar answered Sep 20 '22 02:09

vcsjones