Coginiti menu Coginiti menu

SQL Logical Operators

How Do Logical Operators Work in SQL?

SQL Logical Operators combine conditions in a WHERE clause to create more complex expressions. Operators in SQL can be symbols or keywords used to perform operations on data. They perform various tasks in SQL statements, such as filtering, combining, and modifying data.

These are the SQL Logical Operators:

  • AND – Returns True if both conditions are True.
  • OR – Returns True if either of the conditions is True.
  • NOT – Returns true if the condition is false
AND

The AND operator combines two conditions and returns TRUE if both conditions are TRUE.

SELECT *  
FROM products  
WHERE prices > 50 AND category = 'dresses';  

In this example, the query retrieves all columns and rows from the products table where the prices are greater than 50, and the category is ‘dresses’. Only the products whose cost exceeds 50 and belong to the ‘dresses’ category will be in the result set.

OR

The OR operator combines two conditions and returns TRUE if at least one condition is TRUE.

SELECT *  
FROM products  
WHERE prices = 50 OR category = 'dresses';  

In this example, the query retrieves all columns and rows from the products table where prices are equal to 50 or the category is ‘dresses’. As a result, you will see a mix of all the products that cost 50 and all dresses at any price.

NOT

The NOT operator negates a condition and returns TRUE if the condition is FALSE.

SELECT *  
FROM products  
WHERE NOT category = 'dresses'; 

In this example, the NOT operator negates the condition, so only the products that do not belong in the ‘dresses’ category will be returned.