10

I am writing an INSERT Statement to insert one row into the table in a PL/SQL block. If this insert fails or no row is inserted then I need to rollback the previously executed update statement.

I want to know under what circumstances the INSERT statement could insert 0 rows. If the insert fails due to some exception, I can handle that in the exception block. Are there cases where the INSERT might run successfully but not throw an exception where I need to check whether SQL%ROWCOUNT < 1?

2
  • 2
    Is your INSERT statement an INSERT ... VALUES statement? Or an INSERT ... SELECT? Commented Aug 9, 2012 at 5:11
  • 1
    My INSERT statement is like: INSERT ... VALUES Commented Aug 9, 2012 at 5:53

3 Answers 3

26

If your INSERT statement is structured as an INSERT ... VALUES, then it will either successfully insert exactly one row or generate an exception. There would be no need to check the SQL%ROWCOUNT.

If your INSERT statement is structured as an INSERT ... SELECT, then it is possible that the SELECT statement will return 0 rows, the INSERT statement will insert 0 rows, and no exception will be thrown. If you consider that to be an error, you would need to check the SQL%ROWCOUNT after the INSERT statement runs.

Sign up to request clarification or add additional context in comments.

1 Comment

Excellent answer! I've always wondered how this could happen.
3

Yes, to find out how many rows are affected by DML statements (INSERT, UPDATES etc.), you can check the value of SQL%ROWCOUNT

INSERT INTO TABLE
SELECT col1, col2,....
  FROM TAB;

if SQL%ROWCOUNT=0 then
   RAISE_APPLICATION_ERROR(-20101, 'No records inserted');
end if;

Comments

0

To complete one of above comments:

  • in case if you request INSERT INTO ... VALUES DML statement without any hints, then indeed system will return either 1 row(s) created in case of success or ORA error in case of failure

  • however if you request INSERT INTO ... VALUES DML statement with hint: IGNORE_ROW_ON_DUPE_KEY, then you get either 1 row(s) created or 0 row(s) created in case when the row already exists and ORA error in case of other failures

  • and in case you request INSERT ... SELECT as mentioned above by Justin, you can also expect to get 0 row(s) created as internal call to SELECT can indeed return

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.