August 23, 2024
Logical Operators in SQL
Logical operators in SQL are powerful tools that allow you to combine multiple comparison operators within a single query. They allow you to combine multiple conditions within a query, making it possible to perform more complex searches and data retrieval. Each logical operator has its own unique function and purpose, so it's essential to understand how they work individually. In the following lessons, we'll explore each of these logical operators in detail, helping you master their usage and apply them effectively in your SQL queries.
LIKE Operator
The LIKE operator in SQL is used to match values that are similar, rather than requiring an exact match. It is especially useful when you need to search for patterns within text data. With the LIKE operator, you can find records that partially match a specified value.
Code
SELECT * FROM Sales
WHERE City LIKE 'New%';
IN Operator
The IN operator in SQL allows you to specify a list of values to include in your query results. Instead of using multiple OR conditions, the IN operator lets you efficiently filter data to match any value within a specified list.
Code
SELECT * FROM Sales
WHERE City IN ('Mumbai', 'Delhi', 'Kolkata');
BETWEEN Operator
The BETWEEN operator in SQL allows you to filter and select rows that fall within a specified range of values. It is particularly useful when you want to retrieve records where a column's value lies between two defined limits.
Code
SELECT * FROM Sales
WHERE Day_Sale BETWEEN 50000 AND 100000;
AND Operator
The AND operator in SQL is used to filter and select rows that satisfy multiple conditions simultaneously. When you use AND in a query, only the rows that meet all the specified conditions will be included in the results.
Code
SELECT * FROM Sales
WHERE Age > 25 AND City = 'New York';
OR Operator
The OR operator in SQL allows you to filter and select rows that satisfy at least one of two (or more) conditions. When you use OR in a query, rows that meet any of the specified conditions will be included in the results.
Code
SELECT * FROM Sales
WHERE Designation = 'Sales Executive' OR City = 'Mumbai';
NOT Operator
The NOT operator in SQL is used to filter and select rows that do not match a specified condition. By applying NOT in a query, you can effectively exclude records that meet certain criteria, allowing you to focus on data that falls outside of those conditions.
Code
SELECT * FROM Employees WHERE NOT City = 'Kolkata';