SQL Logical Operator-interview
Q1. What are logical operators in SQL?
Logical operators in SQL are used to combine multiple conditions in a query’s WHERE clause. The main logical operators are AND, OR, and NOT.
- AND returns rows only if all conditions are true.
- OR returns rows if any one condition is true.
- NOT reverses the result of a condition.
Q2. What is the difference between AND and OR operators in SQL?
- The AND operator requires all conditions to be true for a record to be selected.
- The OR operator requires at least one condition to be true.
SELECT * FROM Employees
WHERE Department = 'IT' AND Salary > 50000;
→ Returns employees in the IT department with salaries above 50,000.
SELECT * FROM Employees
WHERE Department = 'IT' OR Department = 'HR';
→ Returns employees from either IT or HR departments.
Q3. How does the NOT operator work in SQL?
The NOT operator inverts the condition result.
SELECT * FROM Employees
WHERE NOT Department = 'HR';
Returns all employees except those in the HR department.
Q4. Can you combine multiple logical operators in a single SQL query?
Yes. Logical operators can be combined for complex conditions. Parentheses () are used to define precedence.
SELECT * FROM Employees
WHERE (Department = 'IT' OR Department = 'HR')
AND Salary > 40000;
Returns employees from IT or HR with salaries above 40,000.
Q5. What is the order of precedence of logical operators in SQL?
SQL evaluates logical operators in the following order:
- NOT
- AND
- OR
Parentheses can be used to override this default precedence.