Skip to main content

And & Or operators

SQL (Structured Query Language) is a powerful tool that allows us to interact with relational databases. In this tutorial, we will focus on two fundamental SQL logical operators: AND and OR. These operators allow us to perform complex queries by combining conditions.

SQL And Operator

The AND operator is used in an SQL statement's WHERE clause. It allows us to filter records based on more than one condition, and it returns a record if all the conditions separated by AND are TRUE.

Here's the syntax:

SELECT column1, column2, ...
FROM table_name
WHERE condition1 AND condition2 AND condition3 ...;

For instance, let's consider the following example. We have a Students table, and we want to select all the students who are in grade 10 and whose age is less than 16.

SELECT *
FROM Students
WHERE Grade = 10 AND Age < 16;

In the above SQL statement, the AND operator connects two conditions: Grade = 10 and Age < 16. The SQL statement returns the records that meet both conditions.

SQL Or Operator

Like the AND operator, the OR operator is used in the WHERE clause. However, it returns a record if any of the conditions separated by OR is TRUE.

Here's the syntax:

SELECT column1, column2, ...
FROM table_name
WHERE condition1 OR condition2 OR condition3 ...;

Let's again consider our Students table. Now we want to select all the students who are either in grade 10 or grade 11.

SELECT *
FROM Students
WHERE Grade = 10 OR Grade = 11;

In the above SQL statement, the OR operator connects two conditions: Grade = 10 and Grade = 11. The SQL statement returns the records that meet either one or both conditions.

Combining And & Or Operators

We can combine AND and OR operators in a SQL statement to perform more complex queries. When combined, SQL evaluates the AND operators first, then the OR operators. However, we can control the order of evaluation by using parentheses ().

Let's consider the following example. We want to select students who are either in grade 10 and less than 16 years of age, or students who are in grade 11 and over 15 years of age.

SELECT *
FROM Students
WHERE (Grade = 10 AND Age < 16) OR (Grade = 11 AND Age > 15);

In the above SQL statement, the conditions in parentheses are evaluated first due to the precedence defined by parentheses.

Conclusion

Understanding and effectively using the AND & OR operators can greatly enhance your ability to generate complex and powerful SQL queries. They provide a means to filter and select data based on multiple conditions, leading to more refined results. As you continue learning SQL, these operators will become an essential part of your toolkit.