augustomen
augustomen

Reputation: 9739

What is the order of evaluation of conditions combining AND/OR in PostgreSQL?

Suppose I have a query combining AND and OR conditions without parenthesis:

SELECT * FROM tbl1
WHERE a = 1 AND b = 2 OR c = 3;

How does PostgreSQL evaluate these conditions? Like (a = 1 AND b = 2) OR c = 3 or a = 1 AND (b = 2 OR c = 3). I couldn't find it anywhere in the documentation.

Note: I'm not purposefully writing an ambiguous query like this. I'm building a tool where the user could potentially create a query like that.

Note 2: If it makes any difference, I'm using PostgreSQL 9.6 in one instance and 11 in another.

Upvotes: 2

Views: 1243

Answers (1)

S-Man
S-Man

Reputation: 23676

AND is stronger than OR, so:

a AND b OR c == (a AND b) OR c

demo:db<>fiddle

a  | b  | c  | a AND b OR c | (a AND b) OR c | a AND (b OR c)
:- | :- | :- | :----------- | :------------- | :-------
f  | f  | f  | f            | f              | f       
f  | f  | t  | t            | t              | f       
f  | t  | f  | f            | f              | f       
f  | t  | t  | t            | t              | f       
t  | f  | f  | f            | f              | f       
t  | f  | t  | t            | t              | t       
t  | t  | f  | t            | t              | t       
t  | t  | t  | t            | t              | t 

That, of course, means in your case:

a = 1 AND b = 2 OR c = 3    ==    (a = 1 AND b = 2) OR c = 3

Upvotes: 4

Related Questions