0

Can there be any proper error handling be implemented into a SQL UNIQUE Constraint? So far i'm obviously getting: Error: Duplicate entry 'test1' for key 'username'

But i'd like to have it display a custom comment if possible

1
  • I don't know PHP but usually you get an error code back from your database driver. For Oracle the error number would be 1, for Postgres 23505, ... Catch the exception, check the error number and act accordingly in the code. Commented Dec 4, 2013 at 16:13

1 Answer 1

2

You should check in your app code before inserting this
row that no other row exists with the same username.

Then if it exists, show the error you want to the user.

Parsing this unique constraint error
(after you get it) is not a good idea.

So do it before, not after.

Sign up to request clarification or add additional context in comments.

4 Comments

Checking the rows first will simply double the work the database is doing. First your application checks it, then upon insert the database checks again. Handling the exception is much more efficient approach. And you don't need to "parse" the error message. You can check the SQLSTATE or error code
Yes, it's double work but I cannot agree with this. Maybe you're looking at it from the DB side only.
But that approach won't solve the problem. If you have multiple transactions then some other session can insert a row between in the time between the check (select) and the actual insert. So you have to check for any error during insert anyway and in the end you wind up with the error checking and the double load on the server - which makes the application non-scalable.
These calls are usually synchronized through other means at the app or some middleware user management service level. You're talking about a typical 2-tier app in mind, I think. If so yes, I agree completely in that context. So anyway, I get your points too.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.