Home sql How to insert a row into a table if it is not...

How to insert a row into a table if it is not already there

Author

Date

Category

I know of two options for INSERT IF NOT EXIST :

IF NOT EXISTS (SELECT * FROM sys where name = 'web')
 BEGIN
  INSERT INTO sys (name, value) VALUES ('web', '14')
 END

and

INSERT IF NOT EXISTS INTO sys (name, value) VALUES ('web', '14')

None is suitable for orakl. Help with implementation

IF NOT EXISTS (SELECT * FROM sys where name = 'web')
 BEGIN
  INSERT INTO sys (name, value) VALUES ('web', '14')
 END

under oracle please


Answer 1, authority 100%

You can do it like this, if you need to do with clean sql :

insert into sys (name, value)
select 'web', '14' from dual where not exists (select 1 from sys where name = 'web')

You can also use merge , it gives you more wiggle room:

merge into sys
using (select 'web' as name, '14' as value from dual) t
on (sys.name = t.name)
when not matched then insert (name, value) values ​​(t.name, t.value)

Small comment on the table name. It is not desirable to name the table SYS in Oracle , it can lead to interesting consequences in the behavior of the IDE

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions