SQL – Logical Operator

Logical Operators are used to combine multiple conditions. There are basically Three Operators namely, AND, OR and NOT. From that ‘AND’ and ‘OR’ combines multiple conditions while NOT is used to represent the Reverse Conditions.

Key Points:

  • All Logical Operator returns the Boolean value (True or False).
  • ‘AND’ and ‘OR’ operators are also known as Conjunctive Operators.
  • The NOT operator reverses the meaning of the logical operator.
  • Logical Operator can be used with Where Clause in SQL, to determine whether a row can be selected or not for operations.

Logical Operators in SQL

OperatorsDescription
ANDReturns True when all the given conditions
becometrue and Returns False when one the
GivenConditions become false.
ORReturns True when one of the given
conditionsbecomes true and Return False
when all theconditions become false.
NOTReturns True when given condition becomes
 false and Returns False when given
condition becomes true.

Example:

  1. Display Information of all Customer who are living in ‘Surat’ or Rating above 200.
Result of Above Query
Result of Above Query
Below Table Explain the Record Selection for above Query on the Basic of Conditions.
Condition-1 Satisfied?Condition-2 Satisfied?Row Selected
YESYESYES
NOYESYES
YESYESYES
  1. List all order taken of salesman 1003 with amount > 1500.
Result of Above Query
Result of Above Query
Below Table Explain the Record Selection for above Query on the Basic of Conditions.
Condition-1 Satisfied?Condition-2 Satisfied?Row Selected
YESYESYES
  1. List Name and City of all Salesman who are not living in ‘London’.
Result of Above Query
Result of Above Query

Nested Logical Operators:

You can use multiple logical operators in an SQL statement. When you combine the logical operators in a SELECT statement, the order in which the statement is processed is
1) NOT                                  2) AND                                         3) OR

Example:

List Name, City and Rating of all Customer with Rating between 100 and 200 OR Not Staying in ‘Surat’.
Result of Above Query
Result of Above Query
In this case, the filter works as follows:
Condition 1: All the customers not staying in ‘Surat’ are selected.
Condition 2:  All the customers with rating between 100 and 200 are selected.
Condition 3: Finally the Result will Display Records which satisfy at least one of the above conditions is returned.

NOTE: The order in which you phrase the condition is important, if the order changes you are likely to get a different result.

No comments:

Post a Comment