Logical Operators
Logical operators combine multiple conditions in one WHERE clause.
They let you express real-world rules clearly.
Core Concepts
flowchart TD
A[Condition A] --> D{Logical operator}
B[Condition B] --> D
D -->|AND| E[Both must be true]
D -->|OR| F[Either can be true]
D -->|NOT| G[Invert condition]
| Operator | Meaning | Example |
|---|---|---|
AND | Both conditions true | status='open' AND severity>=3 |
OR | At least one true | status='open' OR severity>=5 |
NOT | Negate condition | NOT status='closed' |
- AND Example
- OR Example
SELECT title, status, severity
FROM issues_where
WHERE status = 'open' AND severity >= 4;
| title | status | severity |
|---|---|---|
| Crash on save | open | 5 |
SELECT title, status, severity
FROM issues_where
WHERE status = 'closed' OR severity >= 5;
| title | status | severity |
|---|---|---|
| UI typo | closed | 1 |
| Crash on save | open | 5 |
Code Examples
-- Use parentheses to make precedence explicit.
SELECT issue_id, title
FROM issues_where
WHERE (status = 'open' AND severity >= 3)
OR title = 'UI typo';
| issue_id | title |
|---|---|
| 1 | Login bug |
| 2 | UI typo |
| 3 | Crash on save |
SQLite-Specific Nuances
SQLite Nuance
Operator precedence applies in SQLite, so AND is evaluated before OR unless parentheses change grouping.
Common Pitfalls / Best Practices
Pitfall
Writing mixed AND/OR conditions without parentheses and getting unexpected results.
Best Practice
Use parentheses whenever conditions are non-trivial, even if precedence rules would still work.
Quick Challenge
Return issues where status is open but severity is not 3.
View Solution
SELECT issue_id, title, severity
FROM issues_where
WHERE status = 'open' AND NOT severity = 3;
| issue_id | title | severity |
|---|---|---|
| 3 | Crash on save | 5 |