SQL Operators AND, OR, and NOT

Tiempo de lectura: 2 minutos

Reading Time: 2 minutes

Good afternoon!

We continue with tutorials on SQL

The SQL operators AND, OR, and NOT are used to combine multiple conditions in a WHERE clause. Each has a specific function and is used in different situations.

The SQL AND operator is used to combine two or more conditions in a WHERE clause. For a record to be selected, all specified conditions must be met.

For example, if we want to select customers who are over 30 years old and live in California, we can use the following query:

SELECT * 
FROM customers
WHERE age > 30 AND state = 'California';

In this case, only records where the “age” column is greater than 30 and the “state” column is equal to “California” will be selected.

The SQL OR operator is used to combine two or more conditions in a WHERE clause. For a record to be selected, at least one of the specified conditions must be met.

For example, if we want to select customers who are over 30 years old or live in California, we can use the following query:

SELECT * 
FROM customers
WHERE age > 30 OR state = 'California';

In this case, records where the “age” column is greater than 30 or the “state” column is equal to “California” will be selected.

The SQL NOT operator is used to exclude records that meet a certain condition.

For example, if we want to select customers who are not over 30 years old, we can use the following query:

SELECT * 
FROM customers
WHERE NOT age > 30;

In this case, records where the “age” column is not greater than 30 will be selected.

It’s important to consider the precedence order of operators as it can affect the query result. The order of precedence is as follows: NOT, AND, OR. That’s why it’s recommended to use parentheses to ensure the query is executed correctly.

For example, if we want to select customers who are over 30 years old and live in California or New York, but don’t have a salary greater than $5,000, we can use the following query:

SELECT * 
FROM customers
WHERE (age > 30 AND (state = 'California' OR state = 'New York')) AND NOT salary > 5000;

In this case, we use parentheses to ensure the conditions within them are evaluated first. The query will select customers who are over 30 years old, live in California or New York, but don’t have a salary greater than $5,000.

That’s all for today, I hope it helps you,

Happy Sunday! :memo:

Leave a Comment