Sql query with multiple where statements
How can you write an SQL query with multiple WHERE conditions? What is the correct way to combine several filtering criteria in a single SQL statement?
If you're wondering how to write an SQL query with multiple WHERE statements, the key is understanding how to combine multiple conditions properly in a single WHERE clause.
In SQL, you don’t use multiple separate WHERE keywords; instead, you combine several conditions within one WHERE clause using logical operators like AND, OR, and sometimes NOT.
How to use multiple conditions in WHERE:
- Use AND to require all conditions to be true.
- Use OR to allow any one of the conditions to be true.
- Combine AND and OR carefully with parentheses to control the logic.
Example:
Suppose you want to select employees who work in the 'Sales' department and have a salary greater than 50000:
SELECT * FROM employees
WHERE department = 'Sales' AND salary > 50000;
If you want employees who work in 'Sales' or 'Marketing':
SELECT * FROM employees
WHERE department = 'Sales' OR department = 'Marketing';
You can combine multiple conditions like this:
SELECT * FROM employees
WHERE (department = 'Sales' OR department = 'Marketing') AND salary > 50000;
Tips:
- Use parentheses to group conditions and make your intent clear.
- Remember that AND has higher precedence than OR, so parentheses help avoid logic errors.
- You can also use other operators like <, >, IN, BETWEEN in your WHERE conditions.
Summary:
- Multiple WHERE conditions are combined inside a single WHERE clause.
- Use AND and OR to control how conditions interact.
- Parentheses are important for complex logical expressions.