And in SQL
? AND Operator in SQL
The AND operator in SQL is used to combine multiple conditions in a WHERE, HAVING, or ON clause. It returns TRUE only if all conditions are true.
? Syntax
SELECT column1, column2FROM table_nameWHERE condition1 AND condition2;? Example Table: employees
| id | name | department | salary |
|---|---|---|---|
| 1 | Alice | HR | 50000 |
| 2 | Bob | IT | 60000 |
| 3 | Carol | HR | 45000 |
? Example 1: AND in WHERE clause
SELECT name, salaryFROM employeesWHERE department = 'HR' AND salary > 46000;Output:
| name | salary |
|---|---|
| Alice | 50000 |
? Only rows where both conditions are true are selected.
? Example 2: AND with OR
SELECT nameFROM employeesWHERE department = 'IT' OR (department = 'HR' AND salary > 46000);Use parentheses
()to control logic and precedence.
? Key Points
ANDhas higher precedence thanOR.Use
()to group conditions properly.Can be used in:
WHEREHAVINGJOIN ... ONconditions
? More Examples
? In HAVING clause:
SELECT department, COUNT(*) as countFROM employeesGROUP BY departmentHAVING COUNT(*) > 1 AND SUM(salary) > 90000;? In JOIN:
SELECT *FROM employees eJOIN departments d ON e.department = d.name AND d.active = 1;Let me know if you'd like to practice logical conditions or combine AND with NOT, OR, or subqueries!