SQL Server – How to insert a record and make sure it is unique

Your solution:

INSERT INTO Words (Word)
    SELECT @Word
WHERE NOT EXISTS (SELECT WordID FROM Words WHERE Word = @Word)

…is about as good as it gets. You could simplify it to this:

INSERT INTO Words (Word)
    SELECT @Word
WHERE NOT EXISTS (SELECT * FROM Words WHERE Word = @Word)

…because EXISTS doesn’t actually need to return any records, so the query optimiser won’t bother looking at which fields you asked for.

As you mention, however, this isn’t particularly performant, because it’ll lock the whole table during the INSERT. Except that, if you add a unique index (it doesn’t need to be the primary key) to Word, then it’ll only need to lock the relevant pages.

Your best option is to simulate the expected load and look at the performance with SQL Server Profiler. As with any other field, premature optimisation is a bad thing. Define acceptable performance metrics, and then measure before doing anything else.

If that’s still not giving you adequate performance, then there’s a bunch of techniques from the data warehousing field that could help.

Leave a Comment