Search code examples
mysqlsqloperatorsoperator-precedence

How do i provide higher precedence to OR than AND in mysql query where clause?


I want to have a query of the following nature :

"SELECT * FROM table1 where column1=1 OR column2=1 OR column3=1 AND column4=1 OR column5=1";

According to the operator precedence, AND operation will be performed first and then the OR operations. But in my case I want that column1=1 OR column2=1 OR column3=1 --> this and column4=1 OR column5=1 --> this are performed first and the results from these bound by AND operation for the final result.

Can I just add brackets to get higher precedence for OR like in most programming languages or how is this done ?


Solution

  • You need to use brackets and wrap each part, like this:

    SELECT * FROM table1 
    where (column1=1 OR column2=1 OR column3=1) AND (column4=1 OR column5=1)