SQL Logical Operators
SQL Logical Operators are used to combine multiple conditions in SQL queries. These operators help filter results by applying logical conditions to records in a database. Logical operators are mainly used in the WHERE
clause to refine search criteria.
In this tutorial, we will cover the different SQL logical operators, their syntax, and practical examples.
List of SQL Logical Operators
Operator | Description | Example |
---|---|---|
AND | Returns true if both conditions are true | SELECT * FROM students WHERE age > 18 AND grade = 'A'; |
OR | Returns true if at least one condition is true | SELECT * FROM students WHERE age > 18 OR grade = 'A'; |
NOT | Reverses the result of a condition | SELECT * FROM students WHERE NOT grade = 'A'; |
IN | Checks if a value matches any value in a list | SELECT * FROM students WHERE grade IN ('A', 'B'); |
BETWEEN | Checks if a value is within a range | SELECT * FROM students WHERE age BETWEEN 18 AND 22; |
LIKE | Performs pattern matching | SELECT * FROM students WHERE name LIKE 'A%'; |
IS NULL | Checks if a value is NULL | SELECT * FROM students WHERE grade IS NULL; |
Syntax of SQL Logical Operators
The general syntax for using logical operators in SQL queries is:
SELECT column_name(s)
FROM table_name
WHERE condition1 LOGICAL_OPERATOR condition2;
For example, to select students who are older than 18 and have a grade of ‘A’:
SELECT * FROM students
WHERE age > 18 AND grade = 'A';
Step-by-Step Examples Using SQL Logical Operators
1 Using AND Operator
We will create a students
table and insert sample data for demonstration.
CREATE TABLE students (
id INT PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(50),
age INT,
grade CHAR(1)
);
INSERT INTO students (name, age, grade)
VALUES
('Arjun', 20, 'A'),
('Ram', 18, 'B'),
('Priya', 22, 'A'),
('Neha', 19, 'C'),
('Sita', 21, 'B');
Retrieve students who are older than 18 and have a grade of ‘A’:
SELECT * FROM students
WHERE age > 18 AND grade = 'A';
Result: Returns ‘Priya’ because she is older than 18 and has grade ‘A’.
2 Using OR Operator
Retrieve students who are older than 18 or have grade ‘A’:
SELECT * FROM students
WHERE age > 18 OR grade = 'A';
Result: Returns ‘Arjun’, ‘Priya’, and ‘Sita’ because at least one condition is true.
3 Using NOT Operator
Retrieve students who do not have grade ‘A’:
SELECT * FROM students
WHERE NOT grade = 'A';
Result: Returns ‘Ram’, ‘Neha’, and ‘Sita’.
4 Using IN Operator
Retrieve students whose grade is either ‘A’ or ‘B’:
SELECT * FROM students
WHERE grade IN ('A', 'B');
5 Using BETWEEN Operator
Retrieve students aged between 18 and 21:
SELECT * FROM students
WHERE age BETWEEN 18 AND 21;
Conclusion
SQL Logical Operators allow us to combine conditions and refine queries effectively. We explored:
AND
,OR
, andNOT
for logical condition combinations.IN
for matching values within a list.BETWEEN
for range-based filtering.