Loading
SQL Logical Operator
In SQL, Logical Operators are used to combine multiple conditions within the WHERE clause. These operators help retrieve records that meet specific complex criteria, improving data filtering in your queries.



What Are Logical Operators?

Logical operators evaluate conditions and return TRUE, FALSE, or UNKNOWN for each row. They are used to control which rows appear in the final result set based on one or more logical conditions.



Types of SQL Logical Operators

OperatorDescription
ANDReturns TRUE only if all conditions are true
ORReturns TRUE if any condition is true
NOTReverses the result of a condition



Logical AND Operator

Returns rows only when all conditions are satisfied.


Customer Table

Customer IDNamePostal CodeCountry
2Shiva05021America
4Hanuman05023Mexico
1Dhruva05026Japan
3Ganesh05024Mexico



Example: 

SELECT * FROM Customer WHERE Country = 'Mexico' AND CustomerID > 2;

Output:

Customer IDNamePostal CodeCountry
4Hanuman05023Mexico
3Ganesh05024Mexico

Explanation: Shows customers from Mexico whose CustomerID is greater than 2.



Logical OR Operator

Returns rows if at least one condition is true.



Customer Table

Customer IDNameCityCountry
1JamesParisGermany
2WilliamLyonItaly
3DanielBerlinFrance
4OliverMarseilleGermany



Example:

SELECT * FROM Customer WHERE Country = 'Germany' OR City = 'Berlin';

Output:

Customer IDNameCityCountry
1JamesParisGermany
3DanielBerlinFrance
4OliverMarseilleGermany

Explanation: Displays records where the country is Germany or the city is Berlin.



Logical NOT Operator

Returns rows where the condition is NOT true.



Customer Table

IDNameCityCountry
1JamesParisGermany
2DanielBerlinItaly
3OliverMarseilleGermany
4RoseBelgiumFrance



Example: 

SELECT * FROM Customer WHERE NOT Country = 'Germany';

Output:

IDNameCity
Country
2DanielBerlinItaly
4RoseBelgiumFrance

Explanation: Displays customers who do not belong to Germany.



Key Point

  • Use AND when all conditions must be true.
  • Use OR when at least one condition must be true.
  • Use NOT to exclude specific records.
  • Logical operators are essential for writing complex and precise SQL queries.