Combining conditions in SQL

You can have more than one condition in a select statement. You combine conditions using one of the two following keywords:

  • AND : indicates that the row should fulfill both conditions.
  • OR : indicates that the row should fulfill at least one of the conditions.

Example of statement using AND

select *
from clients
where account_type = “key_account”
and city=”bangalore”

In this example only rows that fulfill both conditions (account_type = “key_account”, city=”bangalore”) will be displayed:

  • only rows for which the account_type is equal to “key_account” and for which the city is “bangalore” will be displayed.
  • in all other cases, the row will not be displayed. For example: rows for which the account_type is equal to “key_account” but for which the city is not “bangalore” will not be displayed.

In this example rows that fulfill at least one of the two conditions will be displayed:

  • rows for which the account_type is not equal to “key_account” but for which the city is “bangalore” will be displayed.
  • rows for which the account_type is equal to “key_account” but for which the city is not “bangalore” will be displayed.
  • rows for which the account_type is equal to “key_account” and for which the city is “bangalore” will be displayed.
  • rows for which the account_type is not equal to “key_account” and for which the city is not “bangalore” will NOT be displayed.

Can you have more than one “AND”, or more than one “OR” in the same SQL query?

Yes. You can use as many as you want.

Can you combine conditions using text and conditions using numbers?

Yes you can.

Is the order in which you write the conditions is important?

If you are using only OR in your query, changing the order:

  • will not change the results.
  • may affect the speed at which the database will find the right rows. To get the best speed, put first the conditions that have the less chances to be fulfilled.

If you are using only AND in your query: same thing.
If you are using both AND and OR in your query, you need to have a look at the next lesson : combining AND and OR statements.

 

To test your understanding of this lesson, take the Combining Conditions in SQL Quiz. You can also go to the next lesson about combining OR and AND with 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>

 
 

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