Why does an OR condition return extra rows when I combine it with AND?
Quick answer
SQLite evaluates AND before OR. So priority = 'high' OR owner = 'Mia' AND done = 0 means priority = 'high' OR (owner = 'Mia' AND done = 0). It includes every high-priority row, even completed ones. If you want either high priority or Mia’s tasks, but only when unfinished, write (priority = 'high' OR owner = 'Mia') AND done = 0.
The question, the details, the next step.
A practical checklist
Write the intended rule in plain language, including words such as “both,” “either,” and “only if.”
Mark which conditions belong together before writing the SQL.
Add parentheses around each OR group when an AND condition should apply to the whole group.
Check a row that matches only the first OR condition and a row that matches only the second.
Check a completed row that otherwise matches, to confirm whether it should be included.
A few more useful answers
Does adding parentheses always change the results?
No. Parentheses can make the existing precedence explicit without changing the grouping or results. They change results when they group conditions differently, as in moving parentheses around the OR expression.
What does `A OR (B AND C)` mean in plain language?
A row passes if A is true, or if both B and C are true. C does not restrict rows that already pass A.
What is a quick way to verify the filter?
Use a small set of rows representing the important cases: each OR alternative on its own, both alternatives, and a row that matches an alternative but fails the shared condition. Compare those expected cases with the query results.
Sources
References used for this guide.
- [S1] SQLite SQL Language Expressions — operator precedence sqlite.org · Checked
