Whenever a query in PL/SQL is written where only one row is expected, there are two ways it is often done:
- Use an implicit
SELECT INTO, and check forTOO_MANY_ROWSandNO_DATA_FOUNDexceptions. - 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?
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.