2012-02-03 16:42:00

Quite often you want to insert a record into a table, but only if it doesn’t already exist. OK, you could first do a SELECT query to check for existence and then do the insert, but it’s clumsy and raises the slim possibility of a race condition (what if someone inserted or deleted that record between the check and the insert?). Every RDBMS seems to handle this differently (and some do not at all). In SQL Server, you can do this:

DECLARE value1 INT = 1
DECLARE value2 VARCHAR(100) = 'text'

IF NOT EXISTS (SELECT 1
               FROM   aTable
               WHERE  col1 = value1
               AND    col2 = value2 )
    INSERT INTO aTable 
    ( col1, col2)
    VALUES
    ( value1, value2 )

And in MySQL:

DECLARE value1 INT = 1
DECLARE value2 VARCHAR(100) = 'text'

INSERT INTO aTable ( column1, column2 )
SELECT value1, value2
FROM DUAL WHERE NOT EXISTS ( SELECT column1
                             FROM aTable                            
                             WHERE column1 = value1
                             AND column2 =value2 LIMIT 1 )

Notice that in MySQL you have to use the dummy DUAL table (which suggests to me that this syntax might work in Oracle too; I haven’t tried it).

Copyright © 2025 delaney. All rights reserved.