SQL AND in Where clause

SQL

The AND command is used in the WHERE clause of a SQL statement to filter records based on multiple conditions. It ensures that all conditions specified must be met for a row to be included in the result set.

Syntax:

SELECT column1, column2, ...
FROM table_name
WHERE condition1 AND condition2 AND ...;
  • condition1, condition2, …: The conditions that must be met.

Let’s start by creating a simple database that we’ll use throughout this tutorial. Our database, named “CodingCoursesDB,” consists of two tables: Students and Courses.

Students Table

StudentIDFirstNameLastNameAge
1JohnDoe22
2AliceSmith20
3BobJohnson23

Courses Table

CourseIDCourseNameInstructor
101Introduction to ProgrammingProf. Smith
102Database ManagementProf. Johnson
103Web DevelopmentProf. Brown

SQL AND Command

The SQL AND command allows us to combine multiple conditions in a query. Let’s explore how to use it with practical examples.

Example: Filtering Students by Age and LastName

SELECT * FROM Students
WHERE Age > 20 AND LastName = 'Johnson';

Output:

StudentIDFirstNameLastNameAge
3BobJohnson23

In this example, we retrieve students who are older than 20 and have the last name ‘Johnson.’