Latest web development tutorials

SQL AND & OR Operators

AND & OR operator is used on more than one condition to filter records.


SQL AND & OR Operators

If the first condition and the second condition is satisfied, the AND operator displays a record.

If the first condition and the second condition as long as one is satisfied, the OR operator displays a record.


The demo database

In this tutorial, we will use w3big sample database.

The following is a selected "Websites" table data:

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

AND operator to instantiate

The following SQL statement is selected from the "Websites" list countries "CN" and alexa rank higher than "50" for all Web sites:

Examples

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

Execution output:



OR operator to instantiate

The following SQL statement Select a country from the "Websites" list for the "USA" or "CN" to all customers:

Examples

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

Execution output:



Combined with AND & OR

You can also combine the AND and OR (use parenthesis to form complex expressions).

The following SQL statement is selected from the "Websites" alexa ranking table is greater than "15" and the country "CN" or "USA" all Web sites:

Examples

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

Execution output: