Wellspring
Wellspring

Reputation: 1340

Evaluation flow of multiple conditions in PostgreSQL

I have searched around but have not yet found a specific answer to this question.

IF x = TRUE AND y = TRUE THEN 
    -- DO SOMETHING
END IF;

In the above statement, does plpgsql evaluate y regardless of the value of x? Or does it stop after discovering that x is FALSE?

I know this is a simple question, so probably I've not lit upon the correct search terms for the simple answer. Apologies in advance, if so.

Upvotes: 3

Views: 1353

Answers (1)

tamth
tamth

Reputation: 154

You cannot make any assumptions about the order of evaluation:

The order of evaluation of subexpressions is not defined. In particular, the inputs of an operator or function are not necessarily evaluated left-to-right or in any other fixed order.

Postgres IS smart enough to stop evaluation once the answer is known.

if the result of an expression can be determined by evaluating only some parts of it, then other subexpressions might not be evaluated at all.

It IS possible to control the execution order if necessary. There are several ways to go about it depending upon the context, each with there own set of limitations. For example, one might use a CASE statement in a query.

Please read this: https://www.postgresql.org/docs/current/sql-expressions.html#SYNTAX-EXPRESS-EVAL

Upvotes: 3

Related Questions