SQL AND, OR and NOT Operators
SQL AND, OR and NOT Operators
The AND and OR operators are used to filter records based on more than one condition:
The AND operator displays a record if all the conditions separated by AND are
TRUE.
The OR operator displays a record if any of the conditions separated by OR is
TRUE.
OR Syntax
SELECT column1, column2, ...
FROM table_name
WHERE condition1 OR condition2 OR condition3 ...;
NOT Syntax
SELECT column1, column2, ...
FROM table_name
WHERE NOT condition;
OR Example
SELECT * FROM Customers
WHERE City='Berlin' OR City='München';
NOT Example
SELECT * FROM Customers
WHERE NOT Country='Germany';
The following SQL statement selects all fields from "Customers" where country is "Germany" AND city must be
"Berlin" OR "München" (use parenthesis to form complex expressions):
Example
SELECT * FROM Customers
WHERE Country='Germany' AND (City='Berlin' OR City='München');
Example
SELECT * FROM Customers
WHERE NOT Country='Germany' AND NOT Country='USA';
SQL IN Operator
The IN operator allows you to specify multiple values in a WHERE clause.
IN Syntax
SELECT column_name(s)
FROM table_name
WHERE column_name IN (value1, value2, ...);
Example
SELECT * FROM Customers
WHERE Country IN ('Germany', 'France', 'UK');
The following SQL statement selects all customers that are NOT located in "Germany", "France" or "UK":
Example
SELECT * FROM Customers
WHERE Country NOT IN ('Germany', 'France', 'UK');
WHERE Finds any values that have "or" in any position WHERE CustomerName LIKE '%b%'
CustomerName B in any position
LIKE '%or%'
WHERE Finds any values that have "r" in the second WHERE CustomerName LIKE '_r%'
CustomerName position Should be 2 char length in this exmple
LIKE '_r%'
WHERE Finds any values that start with "a" and are at
CustomerName least 2 characters in length
LIKE 'a_%'
WHERE Finds any values that start with "a" and are at
CustomerName least 3 characters in length
LIKE 'a__%'
WHERE Finds any values that start with "a" and ends
ContactName LIKE with "o"
'a%o'
Here are some examples showing different LIKE operators with '%' and '_' wildcards:
We will have to use the IS NULL and IS NOT NULL operators instead.
IS NULL Syntax
SELECT column_names
FROM table_name
WHERE column_name IS NULL;
SELECT column_names
FROM table_name
WHERE column_name IS NOT NULL;
The following SQL lists all customers with a NULL value in the "Address" field:
Example
The following SQL lists all customers with a value in the "Address" field:
Example