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

OperatorDescriptionExample
ANDReturns true if both conditions are trueSELECT * FROM students WHERE age > 18 AND grade = 'A';
ORReturns true if at least one condition is trueSELECT * FROM students WHERE age > 18 OR grade = 'A';
NOTReverses the result of a conditionSELECT * FROM students WHERE NOT grade = 'A';
INChecks if a value matches any value in a listSELECT * FROM students WHERE grade IN ('A', 'B');
BETWEENChecks if a value is within a rangeSELECT * FROM students WHERE age BETWEEN 18 AND 22;
LIKEPerforms pattern matchingSELECT * FROM students WHERE name LIKE 'A%';
IS NULLChecks if a value is NULLSELECT * FROM students WHERE grade IS NULL;

Syntax of SQL Logical Operators

The general syntax for using logical operators in SQL queries is:

</>
Copy
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’:

</>
Copy
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.

</>
Copy
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’:

</>
Copy
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’:

</>
Copy
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’:

</>
Copy
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’:

</>
Copy
SELECT * FROM students
WHERE grade IN ('A', 'B');

5 Using BETWEEN Operator

Retrieve students aged between 18 and 21:

</>
Copy
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, and NOT for logical condition combinations.
  • IN for matching values within a list.
  • BETWEEN for range-based filtering.