Combining “OR” and “AND” in SQL

Previously we saw how to combine conditions using AND, or using OR.
Let us see how to use both OR and AND in the same SQL query. The most important is to group conditions using parentheses to show the order of conditions.

Example 1:

select *
from clients
where (city=”bangalore” and account_type = “key_account”) or (number_of_employees > 10000 and total_sales >= 500000)

In this select statement, we use parentheses. These parentheses are separating conditions into two groups:

  • Group 1: city=”bangalore” and account_type = “key_account”. What is written in this group is true if the row fulfills both these conditions.
  • Group 2: number_of_employees > 10000 and total_sales >= 500000. What is written in this group is true if the row fulfills both these conditions.

Moreover, there is an OR between the two groups. This means that a row is displayed if what is written in Group 1 is true OR if what is written in Group 2 is true.

As a result, rows are displayed in the following cases:

  • what is written in Group 1 is true and what is written in Group 2 is not true.
  • what is written in Group 1 is not true and what is written in Group 2 is true.
  • what is written in Group 1 is true and what is written in Group 2 is true.

Example 2:

select *
from clients
where (city=”bangalore” or account_type = “key_account”) and (number_of_employees > 10000 or total_sales >= 500000)

The two groups are:

  • Group 1: town=”bangalore” or account_type = “key_account”. What is written in this group is true if the row fulfills at least one of these conditions.
  • Group 2: number_of_employees > 10000 or total_sales >= 500000. What is written in this group is true if the row fulfills at least one of these conditions.

There is an AND between the two groups. This means that a row is displayed if what is written in Group 1 is true and what is written in Group 2 is true.


 

I invite you to go to the next chapter about SQL Join in SQL.
 
Share on:

Something not clear? Ask your question here:

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

 
 

One question on “Combining “OR” and “AND” in SQL


Author:
Last udpated: September 10, 2017
Created: July 27, 2014