SQL AND & OROperators


AND & OR operators are used to filter records based on more than one condition.


SQL AND & OR Operators

If both the first and second conditions are true, the AND operator displays a record.

If at least one of the first and second conditions is true, the OR operator displays a record.


Demo Database

In this tutorial, we will use the EXAMPLE sample database.

Below is a selection from the "Websites" table:

+----+--------------+---------------------------+-------+---------+
| id | name         | url                       | alexa | country |
+----+--------------+---------------------------+-------+---------+
| 1  | Google       | https://www.google.cm/    | 1     | USA     |
| 2  | 淘宝          | https://www.taobao.com/   | 13    | CN      |
| 3  | Example      | http://www.example.com/    | 4689  | CN      |
| 4  | 微博          | http://weibo.com/         | 20    | CN      |
| 5  | Facebook     | https://www.facebook.com/ | 3     | USA     |
+----+--------------+---------------------------+-------+---------+

AND Operator Example

The following SQL statement selects all websites from the "Websites" table with country "CN" and alexa rank greater than "50":

Example

SELECT * FROM Websites WHERE country='CN' AND alexa > 50;

Execution output:



OR Operator Example

The following SQL statement selects all customers from the "Websites" table with country "USA" or "CN":

Example

SELECT * FROM Websites WHERE country='USA' OR country='CN';

Execution output:



Combining AND & OR

You can also combine AND and OR (using parentheses to form complex expressions).

The following SQL statement selects all websites from the "Websites" table where alexa rank is greater than "15" and country is "CN" or "USA":

Example

SELECT * FROM Websites WHERE alexa > 15 AND (country='CN' OR country='USA');

Execution output:

Other Extensions