Sql - Insert if not exists query

Опубликовано: 01 Ноябрь 2024
на канале: Computer Science lectures and tutorials
6,171
12

sql insert if not exists
In many cases we need to insert a row by checking whether it is already available or not. First we need to find a row is present or not. then if it is present, we skip the insert process. If the row is not present, then we insert the row. This query will help to insert rows only if not present. You can use this query directly in your application, where you need to check the presence before insert.

The syntax is :
merge into tblname i
using (select ‘val1' as a1,‘val2' as a2,‘Val3' as a3, …. , ‘valN' as an) d
on i.attribute1=d.a1 when not matched then
insert (Attribute1,Attribute2,Attribute3, …. , AttributeN) values (d.a1,d.a2,d.a3,…,d.an);

The example is
merge into items i
using (select '7' as itemid,'puri' as itemname,'25' as itemcost) d
on d.itemid=i.itemid when not matched then
insert (itemid,name,price) values (d.itemid,d.itemname,d.itemcost);


Like us on FB
https://www.facebook.com/Eddy5SmartSo...
Subscribe Our Channel
   / @computersciencelecturesand4191