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 RUNOOB sample database.
Below is the data selected 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 | Runoob Tutorial | http://www.runoob.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 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 customers 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: