Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

sql

How to use the AND and OR operators in SQL

Maria Elijah

Overview

In SQL, the AND and OR operators are used to select data based on multiple conditions.

The AND operator’s syntax

SELECT column_name
FROM table_name
WHERE condition
AND condition1 AND condition2 AND condition3 ...;

The database displays the data of when all conditions separated by the AND operators are TRUE.

The OR operator’s syntax

SELECT column_name
FROM table_name
WHERE condition
OR condition1 OR condition2 OR condition3 ...;

The database displays the data of when any of the conditions separated by the OR operators is TRUE.

Note: When we combine AND and OR operators, we must always enclose the individual conditions in parenthesis ().

Example

We have a table named Person with columns such as ID, Name, Age, State, and Gender.

Using the AND and OR operators, let’s now retrieve the names of all individuals in their twenties who live in the Lagos or Abuja states.

-- Creating the table
CREATE TABLE Person (
    ID int,
    Name varchar(100),
    Age int,
    Gender varchar(10),
    State varchar(15)
);

-- Inserting the data
INSERT INTO Person
VALUES (1,'Sharon Peller','16','Female','Kogi');
INSERT INTO Person
VALUES (2,'Paul Dons','20','Male','Lagos');
INSERT INTO Person
VALUES (3,'Ameera Abedayo','28','Female','Imo');
INSERT INTO Person
VALUES (4,'Maria Elijah','25','Female','Lagos');
INSERT INTO Person
VALUES (5,'David Hassan','30','Male','Abuja');
INSERT INTO Person
VALUES (6,'Niniola Disu','28','Female','Lagos');
INSERT INTO Person
VALUES (7,'Praise Dominion','26','Female','Abuja');
INSERT INTO Person
VALUES (8,'Divine Favour','29','Female','Abuja');
INSERT INTO Person
VALUES (9,'Praise Steven','31','Female','Lagos');
INSERT INTO Person
VALUES (10,'Joe Smith','16','Male','Lagos');

-- Query 
SELECT Name
FROM Person
WHERE (Age >= 20 AND Age < 30)
AND (State ='Lagos' OR State ='Abuja')
ORDER BY Name;
Example

Explanation

  • Lines 1–7: We create a Person table with ID, Name, Age, Gender, and Statecolumns.

  • Lines 10–29: We insert data into the Person table.

  • Lines 31–35: We filter the names of all individuals in their twenties who live in the Lagos or Abuja states.

    • Condition 1: (age >= 20 AND age < 30) returns only the names of individuals aged 20 to 29.
    • Condition 2: (state ='Lagos' OR state ='Abuja') returns the names of individuals living in either Lagos or Abuja.
    • Finally, we use the AND operator between the two conditions. We combine the results to get the names of individuals in their twenties who live in the Lagos or Abuja states.

RELATED TAGS

sql
RELATED COURSES

View all Courses

Keep Exploring