Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

insert unique values only

I need to find the most efficient way to insert a value into table but only when that value is not already in the table.

here is a sample table:

DECLARE @Table table (TheValue int primary key)

sample data to insert:

INSERT @Table SELECT 1 UNION SELECT 2 UNION SELECT 3 --existing data
DECLARE @x int;set @x=5                              --data to add

here are all the ideas I can think of to do this. Which one is best and/or is there a better way? This is a batch process, so there is no risk of another process inserting data, so no locking is necessary in Try 1.

Try 1:

IF NOT EXISTS (SELECT 1 FROM @Table WHERE TheValue=@x)
BEGIN
    INSERT @Table VALUES (@x)
END

Try 2:

INSERT @Table SELECT @x EXCEPT SELECT TheValue FROM @Table

Try 3:

INSERT @Table SELECT @x WHERE @X NOT IN (SELECT TheValue FROM @Table)

Try 4:

BEGIN TRY
    INSERT @Table VALUES (@x)
END TRY
BEGIN CATCH END CATCH
like image 494
RacerX Avatar asked Feb 04 '26 20:02

RacerX


1 Answers

why not set a unique constraint on that column

like image 153
Sam Axe Avatar answered Feb 06 '26 11:02

Sam Axe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!