14

I've read here that the syntax looks like this:

INSERT
WHEN ([Condition]) THEN
INTO [TableName] ([ColumnName])
VALUES ([VALUES])
ELSE
INTO [TableName] ([ColumnName])
VALUES ([VALUES])
SELECT [ColumnName] FROM [TableName];

But I don't want to provide values from another table. I just want to type them, so I've got:

INSERT 
WHEN EXISTS (SELECT 1 FROM FOO WHERE NAME = 'JOE') 
THEN
INTO BAR (NAME, AGE) 
VALUES ('JOE', 50)

and this produces exception: ORA-00928: missing SELECT keyword.

I want to perform an insert if given value is found in another table.

1
  • I think you can only use that inside a PL/SQL procedure, not in plain SQL. The WHEN clause is not part of the SQL INSERT clause: docs.oracle.com/database/121/SQLRF/…
    – user330315
    Commented Jan 25, 2017 at 11:20

2 Answers 2

17

Using with select works. Your query wasn't working because there is a problem with values keyword when inserting conditionally.

INSERT 
WHEN EXISTS (SELECT 1 FROM FOO WHERE NAME = 'JOE') 
THEN
INTO BAR (NAME, AGE) 
SELECT 'JOE', 50 FROM DUAL
0
5

So, I've found an indirect way here and solution for my question would be:

INSERT INTO BAR (NAME, AGE) 
SELECT 'JOE', 50
  FROM DUAL
 WHERE EXISTS (SELECT 1 FROM FOO WHERE NAME = 'JOE')

but it doesn't explain why I have to use SELECT statement in INSERT WHEN

1
  • I assume it is because this system relies on the INSERT aborting when the SELECT it relies on returns no results.
    – Nyerguds
    Commented Sep 28, 2017 at 12:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.