Question

Is it better to write:

IF EXISTS (SELECT ...) OR EXISTS (SELECT ...)
  BEGIN
    INSERT INTO myTable
    VALUES ('myValue1', 'myValue1')
  END

Or to write:

INSERT INTO myTable
SELECT 'myValue1', 'myValue1'
WHERE EXISTS (SELECT ...) OR EXISTS (SELECT ...)

?

I mean better in terms of performance and readability.

Pileggi

Was it helpful?

Solution

You should use the latter, not really a question of efficiency (I suspect there is no significant difference between the two), but the least likely to meet a race condition. If two inserts run concurrently, there is a small chance that when using the first method the same record is inserted by another thread in between checking if the value exists and actually doing the insert. Since both the check and the insert are done using the same lock in the latter this is less likely to occur.

So in my opinion, both readability and performance come a very distant second in terms of importance to accuracy and thread safety.

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