HiveBrain v1.2.0
Get Started
← Back to all entries
debugsqlMinor

Pros and Cons of Checking if value exist for unique column or let db raise unique error on inserting

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
uniqueinsertingerrorcolumncheckingexistvalueprosletfor

Problem

While writing a query other day a thought came to me and have stuck in my mind.

What is preferable, first checking if a value for a unique column exists and then inserting or insert and let db raise unique constraint error? Will it even matter?

Edit: As suggested below in answer that this issue depends on database I am adding tag postgresql.

Solution

Let the DB raise an error.

Testing first isn't safe for concurrency because you'll get a collision eventually because 2 threads may pass the "NOT EXIST" and both will try to write. This applies to both "READ COMMITTED" and MVCC/Snapshot lock strategies.

You can use lock hints to force isolation, but you reduce performance.

I call this the JFDI pattern (SO link). For "update if exists" then see this here: Need Help Troubleshooting Sql Server 2005 Deadlock Scenario. These are SQL Server. MySQL has INSERT IGNORE which handles this gracefully. Not sure about the rest

Context

StackExchange Database Administrators Q#12551, answer score: 8

Revisions (0)

No revisions yet.