Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 569
Bdfy Avatar asked Apr 26 '12 10:04

Bdfy


People also ask

What is grouping sets in PostgreSQL?

In PostgreSQL, the GROUPING SETS are used to generate a result set equivalent to which generated by the UNION ALL of the multiple GROUP BY clauses. A grouping set is a set of columns by which the user group. Typically, a single aggregate query defines a single grouping set.

Can I have GROUP BY and ORDER BY together in SQL query?

Both GROUP BY and ORDER BY are clauses (or statements) that serve similar functions; that is to sort query results. However, each of these serve very different purposes; so different in fact, that they can be employed separately or together.

Is GROUP BY and aggregate function?

What Is Group By in SQL? The Group By statement is used to group together any rows of a column with the same value stored in them, based on a function specified in the statement. Generally, these functions are one of the aggregate functions such as MAX() and SUM().


2 Answers

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.

like image 81
Raphaël Althaus Avatar answered Oct 03 '22 07:10

Raphaël Althaus


It goes as per the Operator Precendence http://www.postgresql.org/docs/6.5/static/operators.htm#AEN1615.

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

like image 30
Rahul Avatar answered Oct 03 '22 07:10

Rahul