In SQL, the AND operator is used to combine multiple conditions in a WHERE clause. When you use AND, the query will return results only if all the conditions specified are true.
Syntax:
How it works:
- The
ANDoperator ensures that only rows that satisfy every condition are included in the result. - If any of the conditions evaluates to false, that row is excluded.
Example:
Suppose you have a table called employees with columns employee_id, name, age, and department.
Query:
Explanation:
- This query retrieves the names, ages, and departments of employees who are older than 30 and who belong to the HR department.
- Both conditions must be true for a row to be returned.
Multiple Conditions:
You can use the AND operator to combine more than two conditions.
Example:
This query returns the names, ages, and departments of employees who are:
- Older than 25
- In the Finance department
- Have an
employee_idless than 1000
Combining AND with OR:
You can also combine AND with the OR operator for more complex queries. When doing so, it’s important to use parentheses to control the logic of the conditions.
Example:
This query retrieves employees who either:
- Are older than 25 and work in Finance, or
- Work in the HR department (regardless of age).
Key Points:
ANDconditions are evaluated from left to right, and all conditions must be true for the result to be included.- Using
ANDmakes your queries more restrictive, narrowing down the results based on multiple conditions.
No comments:
Post a Comment