0
0
SQLquery~5 mins

Operator precedence in WHERE in SQL

Choose your learning style9 modes available
Introduction
Operator precedence in WHERE helps decide which parts of a condition are checked first, so the database returns the right results.
When you want to filter data using multiple conditions in a query.
When you combine AND and OR in the same WHERE clause.
When you want to make sure certain conditions are checked before others.
When you want to avoid mistakes in filtering data by controlling the order of conditions.
Syntax
SQL
SELECT column1, column2
FROM table_name
WHERE condition1 AND condition2 OR condition3;
AND has higher precedence than OR, so conditions joined by AND are evaluated first.
Use parentheses () to group conditions and control the order explicitly.
Examples
AND is checked before OR, so salary > 50000 applies only to Marketing department.
SQL
SELECT * FROM employees WHERE department = 'Sales' OR department = 'Marketing' AND salary > 50000;
Parentheses change the order: first check if department is Sales or Marketing, then salary > 50000.
SQL
SELECT * FROM employees WHERE (department = 'Sales' OR department = 'Marketing') AND salary > 50000;
price > 100 AND stock > 0 is checked first, then OR discontinued = FALSE.
SQL
SELECT * FROM products WHERE price > 100 AND stock > 0 OR discontinued = FALSE;
Sample Program
This query returns employees in 'Sales' (regardless of salary) or in 'Marketing' with salary over 50000. Because AND has higher precedence, salary > 50000 applies only to Marketing.
SQL
CREATE TABLE employees (
  id INT,
  name VARCHAR(50),
  department VARCHAR(50),
  salary INT
);

INSERT INTO employees VALUES
(1, 'Alice', 'Sales', 60000),
(2, 'Bob', 'Marketing', 45000),
(3, 'Charlie', 'Marketing', 55000),
(4, 'Diana', 'Sales', 40000);

SELECT name, department, salary
FROM employees
WHERE department = 'Sales' OR department = 'Marketing' AND salary > 50000;
OutputSuccess
Important Notes
Always use parentheses to make your conditions clear and avoid confusion.
Remember that AND is checked before OR unless you use parentheses.
Testing your queries with sample data helps you understand how precedence works.
Summary
AND is evaluated before OR in WHERE clauses.
Use parentheses to control the order of condition evaluation.
Operator precedence affects which rows are returned by your query.