SQL OR Operator
The SQL OR operator is used to filter records based on multiple conditions, where at least one condition must be true for the row to be included in the result set.
The OR operator is commonly used in the WHERE clause to broaden the criteria, retrieving records that match any of the specified conditions.
In this tutorial, we will go through OR Operator in SQL, its syntax, and how to use this operator in forming conditions in SQL statements, with well detailed examples.
Syntax of SQL OR Operator
The basic syntax of the SQL OR operator in a WHERE clause is as follows:
SELECT column1, column2, ...
FROM table_name
WHERE condition1 OR condition2 OR ...;
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.
- OR: Combines multiple conditions. Each condition separated by
ORcan 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 OR 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 OR Operator in Queries
Now, let’s explore different scenarios of using the OR operator with this table.
