简体   繁体   中英

Insert a row into the table if it does not exist using SQL

I want to insert a row into the table if it does not exist. I want to check if the col1 , col2 combination exists in the table.If not I have to insert the data.I have written a query like below , but it is not working.Can some one please help me.

INSERT INTO TABLE1 (COL1 , COL2 , COL3, COL4) 
VALUES ( 1234 , 4567 , 'test_name_int' , 'test_disp_name' )
WHERE NOT EXISTS ( SELECT * FROM TABLE1 WHERE COL1 = 1234 and COL2 = '4567');

MERGE INTO is another good option. You could perform update too, if required.

This checks whether col1,col2 of the source and destination match. If they do not,then it does insert . you could also use WHEN MATCHED THEN UPDATE when required to do so.

MERGE INTO TABLE1 d
     USING (SELECT 1235 COL1,
                   4568 COL2,
                   'test_name_int' COL3,
                   'test_disp_name' COL4
              FROM DUAL) s
        ON (d.COL1 = s.col1 AND d.COL2 = s.COL2)
WHEN NOT MATCHED
THEN
   INSERT     (COL1,
               COl2,
               COl3,
               COl4)
       VALUES (s.COl1,
               s.COL2,
               s.COL3,
               s.COL4);

Maybe something like that:

Insert Into TABLE1
Select  1234 , 4567 , 'test_name_int' , 'test_disp_name'
From Dual
WHERE NOT EXISTS ( SELECT * FROM TABLE1 WHERE COL1 = 1234 and COL2 ='4567')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM