Bdfy
Bdfy

Reputation: 24621

Grouping AND and OR conditionals in PostgreSQL

I always use brackets in sql queries. But I have example:

DELETE FROM prog 
WHERE prog_start >= $1 AND prog_start < $2
   OR prog_end > $1 AND prog_end <= $2

Is it equal to :

DELETE FROM prog
WHERE ( prog_start >= $1 AND prog_start < $2 )
   OR ( prog_end > $1 AND prog_end <= $2 ) 

or not ?

Upvotes: 35

Views: 16544

Answers (2)

Rahul
Rahul

Reputation: 77866

It goes as per the Operator Precedence https://www.postgresql.org/docs/current/sql-syntax-lexical.html#SQL-PRECEDENCE.

To form a complex condition it's always better to parenthesis your conditions.

Upvotes: 1

Rapha&#235;l Althaus
Rapha&#235;l Althaus

Reputation: 60493

In SQL the AND operator takes "precedence" over OR operator. PostgreSQL adheres to the spec here. You can the exact precedence in PostgreSQL in the docs Lexical Structure: Operator Precedence.

So in your case, the result will be the same. However, it's much easier, and cleaner to simply use the parentheses.

Upvotes: 45

Related Questions