SQL AND & OR operator

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

SQL AND & OR operator

If both the first condition and the second condition are true, the AND operator displays a record.
If only one of the first condition and the second condition holds, the OR operator displays a record.

Demo database

In this tutorial, we will use the RUNOOB sample database.
The following is the data selected 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 | Rookie Tutorial | http : //www.runoob.COM / | 4689 | CN | | 4 | Twitter | HTTP : //weibo.com/ | 20 | CN | | 5 | Facebook | HTTPS : //www.facebook.com/ | 3 | USA | + --- - + -------------- + --------------------------- + ----- - + --------- +


           
              
          
              
         

AND operator instance

The following SQL statement selects all sites from the "Websites" table for "CN" and alexa rank greater than "50":

Examples

SELECT * FROM Websites WHERE country = ' CN ' AND alexa > 50 ;
Execute the output:


OR operator instance

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

Examples

SELECT * FROM Websites WHERE country = ' USA ' OR country = ' CN ' ;
Execute the output:


Combined with AND & OR

You can also combine AND and OR (using parentheses to form complex expressions).
The following SQL statement selects all sites with alexa rank greater than "15" and "CN" or "USA" from the "Websites" table:

Examples

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


EmoticonEmoticon