user4181107
user4181107

Reputation: 401

Is it redundant to check if a value is unique in both the application and database?

So let's say a user registers for an account, I would like to check if the email being used is already associated with another account...

On the database side, I put a unique constraint on the email column. Now on the application side, should I run a query to check whether that email is already in use and then if it isn't, run another query to insert the user? Or should I ignore that step and since I already have a unique constraint in the database column, I should just attempt to insert the user and if I get an error, I know the email is already in use?

Is running a query just to check for the email being redundant or is it a necessary step and why?

I am using PHP and MySQL.

Upvotes: 0

Views: 72

Answers (1)

bishop
bishop

Reputation: 39414

Yes, it's redundant, but you might want to do it.

You have two choices, really:

  1. Check in app, then add to database. There is a race condition there, so you need to Wrap the check-set in an application level mutex, or
  2. Just push into the database and catch any exception raised from the database layer and handle (taking care to distinguish between constraint violation on column exceptions from all other kinds of possible run time exceptions).

Depending upon the relative ease of these two approaches, decide which works for you.

Upvotes: 1

Related Questions