Skip to content

Option to avoid attempting to insert duplicate rows #14464

Closed as duplicate
Closed as duplicate

Description

@divega

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.

Activity

  1. divega commented on Jan 19, 2019

    @divega
    ContributorAuthor
  2. ajcvickers commented on Jan 19, 2019

    @ajcvickers
    Contributor

    @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...)

  3. divega commented on Jan 19, 2019

    @divega
    ContributorAuthor

    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.

  4. added this to the Backlog milestone on Jan 23, 2019
  5. roji commented on Oct 19, 2022

    @roji
    Member

    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.

  6. roji commented on Oct 19, 2022

    @roji
    Member

    Duplicate of #16949

  7. removed this from the Backlog milestone on Oct 19, 2022
  8. removed their assignment
    on Oct 19, 2022
  9. added theissue type on Jun 15, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions