Question

I have a general database programming theory question that I hope isn’t too off base for stack overflow. One of the tables in my database holds a uniques string. I have indicated in MySQL that this field is Unique. When trying to add the same data again - on purpose - I get the proper Duplicate entry message and the data is not added. My question is, is it better to use this database feature, uniqueness, versus inserting a few statements in my code to look up the string and check if the string has been saved previously...

Thanks in advance for your help.

Jeff

Was it helpful?

Solution

No.

What if someone else adds it between your if check and your INSERT query?

Part of the point of database-level constraints is to be atomic – to check the constraint and perform the insert at the same time, so no-one else can interfere in the middle.

OTHER TIPS

I would say in the case of a relational database like MySQL, it is absolutely the right decision to have the database enforce the uniqueness of a column.

Enforcing data integrity is a main feature of databases, and unique columns are an integral part of this ability. In the case of a key column, there are also performance benefits of looking up records by id when the enforcement lives in the db.

Finally, when you're running a distributed application where many users can simultaneously create records, you get the unique guarantee for free, instead of having to synchronize key creation yourself.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top