SQL - Logical Operators
In SQL Server, logical operators are used to combine multiple conditions or Boolean expressions to form more complex conditions. These operators allow you to perform logical operations on the results of comparisons or conditions. The following logical operators are available in SQL Server:
1-AND: Returns true if both conditions on either side of the operator are true.
Example:
SELECT * FROM Customers WHERE Country = 'USA' AND City = 'New York';
2-OR: Returns true if at least one of the conditions on either side of the operator is true.
Example:
SELECT * FROM Customers WHERE Country = 'USA' OR Country = 'Canada';
3-NOT: Negates the result of a condition or Boolean expression.
Example:
SELECT * FROM Customers WHERE NOT Country = 'USA';
4-EXISTS: Checks if a subquery returns any rows. It is typically used in combination with a correlated subquery.
Example:
SELECT * FROM Orders o WHERE EXISTS (SELECT 1 FROM Customers c WHERE c.CustomerID = o.CustomerID);
5-IN: Checks if a value matches any value in a subquery or a list of values.
Example:
SELECT * FROM Customers WHERE Country IN ('USA', 'Canada', 'Mexico');
6-BETWEEN: Checks if a value is within a specified range.
Example:
SELECT * FROM Products WHERE UnitPrice BETWEEN 10.00 AND 20.00;
7-LIKE: Checks if a string value matches a specified pattern. It is commonly used with wildcard characters (% and _).
Example:
SELECT * FROM Products WHERE ProductName LIKE 'Apple%';
These logical operators can be used in combination with comparison operators, parentheses, and other logical operators to create complex conditions and control the flow of data retrieval in SQL Server. They are commonly used in WHERE clauses, JOIN conditions, and HAVING clauses to filter and manipulate data based on specific logical conditions.