SQL AND, OR, and NOT Operators

In this tutorial, we'll learn to use the AND, OR, and NOT operators in SQL with the help of various examples.

The AND, OR and NOT operators in SQL are used with the WHERE or HAVING clauses.


SQL AND Operator

The SQL AND operator selects data if all conditions are TRUE. For example,

SELECT first_name, last_name
FROM Customers
WHERE country = 'USA' AND last_name = 'Doe';

Here, the SQL command selects first_name and last_name of all customers where the country is USA and last_name as Doe from the Customers table.

How to use the AND operator in SQL?
Example: SQL AND Operator

SQL OR Operator

The SQL OR operator selects data if any one condition is TRUE. For example,

SELECT first_name, last_name
FROM Customers
WHERE country = 'USA' OR last_name = 'Doe';

Here, the SQL command selects first_name and last_name of all customers where the country is USA or if their last name is Doe from the Customers table.

How to use the OR operator in SQL?
Example: SQL OR Operator

SQL NOT Operator

The SQL NOT operator selects data if the given condition is FALSE. For example

SELECT first_name, last_name
FROM Customers
WHERE NOT country = 'USA';

Here, the SQL command selects first_name and last_name of all customers where the country is not USA from the Customers table.

How to use the NOT operator in SQL?
Example: SQL NOT Operator

Combining Multiple Operators

It is also possible to combine multiple AND, OR and NOT operators in an SQL statement. For example,

Let's suppose we want to select customers where the country is either USA or UK, and the age is less than 26.

SELECT *
FROM Customers
WHERE (country = 'USA' OR country = 'UK') AND age < 26;
How to use AND and OR operators together in SQL?
Example: SQL AND and OR Operators

Let's take a look at another example

SELECT *
FROM Customers
WHERE NOT country = 'USA' AND NOT last_name = 'Doe';

Here, the SQL command selects all customers where the country is not USA and last_name is not Doe from the Customers table.

How to use AND and NOT operators together in SQL?
Example: SQL AND and NOT Operators
Did you find this article helpful?