SQL Server BasicsWhat is SQL Server database?What is RDBMS?What is Normalization?Why we use Denormalization?What_is_SQL?What is PL/SQL?Difference between SQL and PL/SQLDatabase TableOne to One RelationshipOne to Many RelationshipMany to Many RelationshipMany to One RelationshipString Data TypesNumber Data TypesDate Data TypesOther Data TypesCreate DatabaseDrop DatabaseCreating and Managing Users in SQL ServerCreate TableAlter TableDrop TableConstraints in SQL serverPrimary KeyForeign KeyUnique KeyCandidate KeyComposite KeyDifference between primary key and candidate keyPrimary key and foreign key relationshipSurrogate KeyCascading Referential Integrity ConstraintsSelf Referential Integrity ConstraintsInsert into statementInsert multiple recordsUpdate statementDelete statementTruncate statementDifference between Delete and TruncateAlias in SQL ServerSelect statementSelect DistinctSelect TopSelect IntoNull Functions(ISNULL(),NULLIF(),COALESCE())Sub QueryIdentity ColumnSequence objectDifference between sequence and identity columnSQL Server ClausesWHERE ClauseOrder By ClauseTop N ClauseGroup By ClauseHaving ClauseDifference between Where and HavingSQL Server OperatorsArithmetic OperatorsComparison OperatorsLogical OperatorsBitwise OperatorsAny OperatorsAll OperatorsUnion OperatorsUnion All OperatorsDifference between Union and Union AllIntersect OperatorExcept OperatorDifference between Except and IntersectJoinsInner JoinLeft JoinRight JoinFull JoinSelf JoinCross JoinViewsWhat are views?Create views using SSMSIndexed ViewsComplex ViewsCheck Option in ViewCheck Encryption in ViewSchema Binding Option in ViewRead-only ViewsUpdatable ViewsAdvantages and disadvantages of viewsCreate multiple views on one tableCan we implement index on views?Can we Perform Insert, update, delete operation on views?Stored Procedure and FunctionsWhat are Stored Procedures?Why we use stored procedures?Passing parameters to Stored procedureUser-Defined FunctionsDifference between UDF and Stored procedurePre-Defined Functions@@Indentity and Scope_IndentityNULLIF, ISNULL and COALESCE

Mastering SQL Logical Operators: A Comprehensive Guide with Examples

What Are Logical Operators?

Logical operators in SQL are used to combine or manipulate Boolean expressions (conditions that evaluate to TRUE, FALSE, or NULL). They help you create more complex conditions by linking multiple simple conditions together. Logical operators are commonly used in WHERE, HAVING, and JOIN clauses to filter and retrieve data based on specific requirements.

Common SQL Logical Operators

Here are the most commonly used logical operators in SQL:

  • AND
  • OR
  • NOT
  • EXISTS
  • IN
  • BETWEEN
  • LIKE

Let’s explore each operator in detail with examples.

1. AND Operator

The AND operator returns TRUE only if all the conditions on either side of the operator are true. It’s used when you want to combine multiple conditions, and all of them must be satisfied.

Example:


SELECT * 
FROM Customers 
WHERE Country = 'USA' AND City = 'New York';
	

Explanation:

  • This query retrieves all customers who are both from the USA and live in New York.
  • If a customer is from the USA but not from New York (or vice versa), they won’t be included in the result.

2. OR Operator

The OR operator returns TRUE if at least one of the conditions on either side of the operator is true. It’s used when you want to retrieve rows that satisfy any of the specified conditions.

Example:


SELECT * 
FROM Customers 
WHERE Country = 'USA' OR Country = 'Canada';
	

Explanation:

  • This query retrieves all customers who are either from the USA or Canada.
  • If a customer is from the USA, Canada, or both, they will be included in the result.

3. NOT Operator

The NOT operator negates the result of a condition. It returns TRUE if the condition is FALSE, and vice versa. It’s used to exclude rows that meet a specific condition.

Example:


SELECT * 
FROM Customers 
WHERE NOT Country = 'USA';
	

Explanation:

  • This query retrieves all customers who are not from the USA.
  • Customers from any country other than the USA will be included in the result.

4. EXISTS Operator

The EXISTS operator checks if a subquery returns any rows. It’s often used with correlated subqueries to test for the existence of related data in another table.

Example:


SELECT * 
FROM Orders o 
WHERE EXISTS (
SELECT 1 
FROM Customers c 
WHERE c.CustomerID = o.CustomerID
);
	

Explanation:

  • This query retrieves all orders where the customer exists in the Customers table.
  • The subquery checks if there’s a matching CustomerID in the Customers table for each order.

5. IN Operator

The IN operator checks if a value matches any value in a list or a subquery. It’s a shorthand for multiple OR conditions.

Example:


SELECT * 
FROM Customers 
WHERE Country IN ('USA', 'Canada', 'Mexico');
	

Explanation:

  • This query retrieves all customers from the USA, Canada, or Mexico.
  • It’s equivalent to writing:
    
    WHERE Country = 'USA' OR Country = 'Canada' OR Country = 'Mexico';
    			

6. BETWEEN Operator

The BETWEEN operator checks if a value falls within a specified range (inclusive). It’s commonly used with numeric, date, or time values.

Example:


SELECT * 
FROM Products 
WHERE UnitPrice BETWEEN 10.00 AND 20.00;
	

Explanation:

  • This query retrieves all products with a unit price between $10.00 and $20.00 (including $10.00 and $20.00).
  • It’s equivalent to writing:
    
    WHERE UnitPrice >= 10.00 AND UnitPrice <= 20.00;
    			

7. LIKE Operator

The LIKE operator checks if a string value matches a specified pattern. It’s commonly used with wildcard characters:

  • %: Matches zero or more characters.
  • _: Matches exactly one character.

Example:


SELECT * 
FROM Products 
WHERE ProductName LIKE 'Apple%';
	

Explanation:

  • This query retrieves all products whose names start with "Apple" (e.g., "Apple Juice", "Apple Pie").
  • The % wildcard allows for any characters to follow "Apple".

Combining Logical Operators

You can combine multiple logical operators to create complex conditions. Use parentheses () to define the order of evaluation.

Example:


SELECT * 
FROM Customers 
WHERE (Country = 'USA' AND City = 'New York') 
OR (Country = 'Canada' AND City = 'Toronto');
	

Explanation:

  • This query retrieves customers who are either from New York, USA, or Toronto, Canada.
  • The parentheses ensure that the conditions are evaluated correctly.

Practical Use Cases for Logical Operators

Logical operators are incredibly versatile and can be used in various scenarios, such as:

  • Filtering Data: Retrieve specific rows based on multiple conditions.
  • Data Validation: Check if data meets certain criteria.
  • Complex Queries: Combine conditions to create advanced filtering logic.
  • Subqueries: Use with EXISTS or IN to check for related data.

Conclusion

Logical operators are fundamental to writing effective SQL queries. By mastering operators like AND, OR, NOT, EXISTS, IN, BETWEEN, and LIKE, you can create powerful and flexible queries to retrieve and manipulate data. Whether you’re filtering data, validating records, or building complex conditions, logical operators are your go-to tools.

With the examples and explanations provided in this guide, you’re now equipped to use logical operators confidently in your SQL queries. Happy querying!