Use IF...ELSIF only to test a single, simple condition

Link to this posting

Postby Ursego » 30 Jul 2019, 12:29

From the book "PL/SQL Best Practices":

The real world is very complicated; the software we write is supposed to map those complexities into applications. The result is that we often end up needing to deal with convoluted logical expressions. You should write your IF statements in such a way as to keep them as straightforward and understandable as possible. For example, expressions are often more readable and understandable when they are stated in a positive form. Consequently, you are probably better off avoiding the NOT operator in conditional expressions.


It's not at all uncommon to write or maintain code that's structured like this:

Code: Select all
IF condA AND NOT (condB OR condC) THEN
ELSIF condA AND (condB OR condC) THEN

It's also fairly common to get a headache trying to make sense of all of that. You can often reduce the trauma of headache by trading off the simplicity of the IF statement itself (one level of IF and ELSIF conditions) for the simplicity of clauses within multiple levels:

Code: Select all
   IF (condB OR condC) THEN
   END IF;

Don't forget, by the way, to take into account the possibility of your expressions evaluating to NULL. This can throw a monkey wrench into your conditional processing.

An Exception to the Rule

A notable exception to this best practice is when you need to negate a large AND expression in order to find out efficiently whether one value out of a group is different. For example, I recently needed to test the counts of 10 parallel index-by tables, to see if even one of them was different; if so, it was an error. Because AND expressions short-circuit on FALSE (whereas ORs short-circuit on TRUE), this was more efficient than using a group of ORs. Moreover, the logic read more naturally. For example:

Code: Select all
IF NOT (arr1.count = arr2.count
   AND arr1.count = arr3.count
   AND arr1.count = arr4.count AND . . .
   AND arr1.count = arr10.count) THEN RAISE e_missing_value;


Following this best practice will make your code easier to read and maintain. Breaking an expression into smaller pieces can aid maintainability; if and when the logic changes, you can change one IF clause without affecting the logic of others.


Multiple levels of nested IF statements can also decrease readability. You need to strive for a workable balance.
User avatar
Site Admin
Posts: 131
Joined: 19 Feb 2013, 20:33

IF you want to ((lose weight) OR (have unbelievable (brain function AND mental clarity))) THEN click:

free counters

eXTReMe Tracker