Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pros/cons using cursor approach vs. begin-end-exception approach for single-row queries in PL/SQL

Tags:

oracle

plsql

Whenever a query in PL/SQL is written where only one row is expected, there are two ways it is often done:

  1. Use an implicit SELECT INTO, and check for TOO_MANY_ROWS and NO_DATA_FOUND exceptions.
  2. Use an explicit cursor and just fetch the first row from the cursor.

Though both the approaches yield the same result, what are the pros and cons of these approaches?

like image 287
poddroid Avatar asked May 23 '11 13:05

poddroid


People also ask

What is the advantage of cursor in Oracle?

Use of Cursor The major function of a cursor is to retrieve data, one row at a time, from a result set, unlike the SQL commands which operate on all the rows in the result set at one time. Cursors are used when the user needs to update records in a singleton fashion or in a row by row manner, in a database table.

What is the benefit of using cursors?

Cursors are used by database programmers to process individual rows returned by database system queries. Cursors enable manipulation of whole result sets at once. In this scenario, a cursor enables the sequential processing of rows in a result set.

What is one of the advantages of using parameters with a cursor?

What is one of the advantages of using parameters with a cursor? You can use a cursor FOR loop. You can declare the cursor FOR UPDATE. You do not need to DECLARE the cursor at all.

Is it good to use cursor in SQL?

Cursors could be used in some applications for serialized operations as shown in example above, but generally they should be avoided because they bring a negative impact on performance, especially when operating on a large sets of data.


1 Answers

When a select statement is expected to return exactly one row then a "SELECT INTO" is the better approach. Yes, many developers prefer to use a cursor and fetch only one row because it saves them the "bother" of dealing with NO_DATA_FOUND - i.e. they sweep the problem under the carpet and leave the user with a mysterious bug. I blogged about this bad practice* recently.

(* a bad practice that is often sadly enshrined in project PL/SQL standards!)

As for counting and then querying, that just doubles the work so is to be avoided too.

like image 180
Tony Andrews Avatar answered Oct 11 '22 07:10

Tony Andrews