You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Option to avoid attempting to insert duplicate rows #14464
We talked recently about having an alternative to detect when an insert operation would insert duplicate data (e.g. violate a unique constrain) without relying on an exception.
I ran today into this pattern that works with SQL Server, and seems relatively clean:
INSERT INTO Users (UserName, Email)
SELECT @UserName, @Email
EXCEPT
SELECT UserName, Email
FROM Users
WHERE Email = @Email
This will insert 0 rows if there is a conflict in the @Email (that is supposed to be Unique). The idea is to check for rows affected to detect that the INSERT didn't happen, at which point EF Core can handle the case as appropriate (e.g. throw a provider-agnostic exception).
Not sure how this performs or how provider agnostic it can be. This is obviously for a single INSERT, but perhaps there is a similar pattern that would work with batching.
Reacted by Arthur Vickers, bugproof, angrifel, Lee Blundell, Erik Bard and Mykhailo Sulikovskyi
@divega Nice. You posted this at exactly the same time that I was thinking about this scenario again! (It was a bit creepy that it popped up when it did, actually. Hope you're not a telepath...)
The precise issue covering this is "add or ignore" (#16949), which is indeed closely related to upsert. Am closing this issue as a duplicate of that and will add the above notes there.
Activity
divega commentedon Jan 19, 2019
cc @DamianEdwards @davidfowl
ajcvickers commentedon Jan 19, 2019
@divega Nice. You posted this at exactly the same time that I was thinking about this scenario again! (It was a bit creepy that it popped up when it did, actually. Hope you're not a telepath...)
divega commentedon Jan 19, 2019
I hope I am not 🤞
BTW, this article is a more complete survey of the approaches:
http://cc.davelozinski.com/sql/fastest-way-to-insert-new-records-where-one-doesnt-already-exist
It seems using a JOIN can be faster, except that is when inserting data from another table that contains a bunch of rows.
bugproof commentedon Feb 23, 2019
there's also something like UPSERT https://github.com/artiomchi/FlexLabs.Upsert
roji commentedon Oct 19, 2022
The precise issue covering this is "add or ignore" (#16949), which is indeed closely related to upsert. Am closing this issue as a duplicate of that and will add the above notes there.
roji commentedon Oct 19, 2022
Duplicate of #16949