Indexes Arenโt Simple โ Theyโre Strategic
๐ ๐ช๐จ๐๐ ๐ฉ๐ค ๐ฉ๐๐๐ฃ๐ ๐๐ฃ๐๐๐ญ๐๐จ ๐๐ฃ ๐๐๐ฉ๐๐๐๐จ๐๐จ ๐ฌ๐๐ง๐ ๐จ๐๐ข๐ฅ๐ก๐: ๐ "๐๐๐๐ฎ ๐๐ข๐ฅ๐ง๐ค๐ซ๐ ๐ง๐๐๐ ๐ฅ๐๐ง๐๐ค๐ง๐ข๐๐ฃ๐๐" ๐ "๐๐ค๐ค ๐ข๐๐ฃ๐ฎ ๐๐ฃ๐๐๐ญ๐๐จ ๐จ๐ก๐ค๐ฌ ๐๐ค๐ฌ๐ฃ ๐ฌ๐ง๐๐ฉ๐๐จ" Thatโs itโฆ or so I thought. While working on a recent feature, I realized thereโs much more depth to how indexes actually work โ especially how you define them. One key thing I learned from my lead is that: The order of columns in an index matters A LOT.
Example:
CREATE INDEX idx_abc ON table(col_a, col_b, col_c); This works efficiently for:
โ WHERE col_a = ? โ WHERE col_a = ? AND col_b = ? โ WHERE col_a = ? AND col_b = ? AND col_c = ?
But surprisingly:
โ WHERE col_b = ? โ WHERE col_c = ?
๐ Because indexes follow a left-to-right (prefix) rule.
Another mistake I used to overlook:
If most queries are like: WHERE col_a = ? AND col_b = ?
But your index is: (col_z, col_a, col_b)
๐ That index might not be useful at all.
๐ก Big takeaway for me:
Indexes are not just about adding them. Theyโre about designing them based on query patterns.
- What columns are filtered most?
- In what order are they used?
- How selective are they?
Also learned: Every index comes with a tradeoff. More indexes = โฌ Faster reads โฌ Slower writes (INSERT / UPDATE / DELETE need to maintain them)
Still learning, but this completely changed how I think about performance.