# 3.2 Sargability ![The Banana in the Safe](assets/arch_sargability_banana.png) The most important lesson in database laziness is **Sargability** (Search ARGument ABLE). It is the art of asking a question in a way that allows the elephant to use his shortcuts. ## The Peeled Banana (Sargable) Imagine a perfectly peeled banana sitting on a stool. The elephant can just pick it up and eat it. When you say `WHERE id = 5`, this is **SARGABLE**. The mouse librarian can look at the B-Tree and tell the elephant exactly which suitcase to grab. ## The Banana in the Safe (Non-Sargable) Now imagine an identical banana locked inside a complex, high-tech steel safe with a mathematical equation on the door. The elephant cannot eat the banana until it solves the equation. When you say `WHERE id + 1 = 6`, this is **NON-SARGABLE**. Even though _you_ know it means `id=5`, the elephant doesn't take risks. It has to take _every single suitcase_ in the warehouse, pull out the `id`, add 1 to it, and see if it equals 6. It cannot use an index because the index is built on `id`, not on `id + 1`. ## Common Crimes Against Laziness | Crime | Why it’s Non-Sargable | The Lazy Alternative | | :-------------------------------------- | :----------------------------------------------- | :--------------------------------------------------------------- | | `WHERE lower(name) = 'bob'` | Must run `lower()` on every row first. | Use an expression index or `WHERE name = 'Bob'`. | | `WHERE date + interval '1 day' > now()` | Must do math on every row. | `WHERE date > now() - interval '1 day'`. | | `WHERE name LIKE '%smith%'` | Cannot use a standard B-Tree for middle-matches. | Use a [[Chapter 2/2.2 - GIN & GiST (The Word Scavenger) | Remember: if you put a function on the left side of the equals sign, you are putting a banana in a safe. Don't do that to the elephant. --- [[Chapter 3/3.1 - The Lazy General's Map|← 3.1 - The Lazy General's Map]] | [[Chapter 3/3.0 - The Battle for Efficiency|↑ 3.0 - The Battle for Efficiency]] | [[Chapter 3/3.3 - The Soldiers|3.3 - The Soldiers β†’]]