SQL AND & OR
Operators
The AND & OR operators are used to filter records based on more than one condition.
SQL AND & OR Operators
The AND operator displays a record if both the first condition and the second condition are true.
The OR operator displays a record if either the first condition or the second condition is true.
Demonstration Database
In this tutorial, we will use the tutorialpro sample database.
Below is the data from the "Websites" table:
+----+--------------+---------------------------+-------+---------+
| id | name | url | alexa | country |
+----+--------------+---------------------------+-------+---------+
| 1 | Google | https://www.google.cm/ | 1 | USA |
| 2 | Taobao | https://www.taobao.com/ | 13 | CN |
| 3 | tutorialpro.org | http://www.tutorialpro.org/ | 4689 | CN |
| 4 | Weibo | 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 where the country is "CN" and the alexa rank is greater than "50":
Example
SELECT * FROM Websites
WHERE country='CN'
AND alexa > 50;
Execution output:
OR Operator Example
The following SQL statement selects all websites from the "Websites" table where the country is "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 the alexa rank is greater than "15" and the country is "CN" or "USA":
Example
SELECT * FROM Websites
WHERE alexa > 15
AND (country='CN' OR country='USA');
Execution output: