Sargable
- SQL course
- Advanced
- Lesson 69/81
- 4 min
Write conditions that use indexes.
Sargable
A sargable query can use indexes. WHERE price * 2 > 100 is not sargable.
-- Sargable: WHERE price > 50
-- Non-sargable: WHERE price * 2 > 100Sargable indexed, non-sargable not.
Sargable — details
Putting a column in a function breaks the index. WHERE UPPER(name) = 'A' skips the index.
Instead, transform the value on the other side (WHERE name = 'a') or create an index on the expression: CREATE INDEX ON customers (UPPER(name)).
Practice Sargable
Write a sargable query with WHERE price > 50 (uses index).
Starter code
-- write the sargable query here
-- use the price > 50 conditionSample solution
SELECT * FROM products WHERE price > 50;Expected output
name price Laptop 1500
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which query is non-sargable?
- WHERE price > 50
- WHERE id = 5
- WHERE name = 'A'
- WHERE price * 2 > 100 Correct answer
Explanation: Putting a column in a function breaks sargability.
2 sargable
____ → uses an index
sargable → uses an index
Explanation: sargable is the right answer.
3 Sargable: match the terms
| Term | Meaning |
|---|---|
sargable |
indexed |
function |
breaks |
price > 50 |
sargable |
price * 2 |
not |