SQL AND Operator
The SQL AND operator is used to filter records based on multiple conditions. When using AND in a query, each specified condition must be true for the row to be included in the result set. The AND operator is often used in the WHERE clause to apply more than one condition to refine search results.
In this tutorial, we will go through AND Operator in SQL, its syntax, and how to use this operator in forming conditions in SQL statements, with well detailed examples.
Syntax of SQL AND Operator
The basic syntax of the SQL AND operator in a WHERE clause is as follows:
SELECT column1, column2, ...
FROM table_name
WHERE condition1 AND condition2 AND ...;
Each part of this syntax has a specific purpose:
- SELECT: Specifies the columns to retrieve from the table.
- FROM: Specifies the table from which to retrieve data.
- WHERE: Introduces the conditions used to filter the data.
- AND: Combines multiple conditions. Each condition separated by
ANDmust be true for a row to be included in the results.
Step-by-Step Examples with MySQL
We’ll go through various examples demonstrating the AND operator in MySQL. Using MySQL 8.0 with MySQL Workbench, we’ll use a sample students table with fields id, name, age, grade, and locality.
Setup for Examples: Creating the Database and Table
1. Open MySQL Workbench and create a new database:
CREATE DATABASE school;
2. Select the school database:
USE school;
3. Create a table named students:
CREATE TABLE students (
id INT PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(50),
age INT,
grade VARCHAR(10),
locality VARCHAR(50)
);
4. Insert some sample records to use in our examples:
INSERT INTO students (name, age, grade, locality)
VALUES
('Alice', 14, '8th', 'Northside'),
('Bob', 15, '9th', 'Westend'),
('Charlie', 14, '8th', 'Northside'),
('David', 16, '10th', 'Southend'),
('Eva', 15, '9th', 'Westend');
Examples: Using AND Operator in Queries
Now, let’s explore different scenarios of using the AND operator with this table.
