🚀 SQL Indexing: From “it makes queries faster” to actually understanding why For a long time, I used to hear: “Just add an index — your query will be faster.” But I never really understood what actually changes under the hood. Recently, I explored this using EXPLAIN ANALYZE — and the difference was eye-opening. 🧠 Before indexing SELECT * FROM marks WHERE name = 'Chinu'; Execution plan: ➡️ Parallel Sequential Scan - The database scans the entire table - Checks every row - Cost grows linearly with data size ⏱️ Higher execution time as data increases ⚡ After adding an index CREATE INDEX idx_name ON marks(name); Execution plan: ➡️ Index Scan - Uses a B-Tree structure internally - Navigates like a search tree (O(log n)) - Directly jumps to matching rows ⏱️ Significant performance improvement 🔍 Going one step further — Covering Index CREATE INDEX idx_name ON marks(name) INCLUDE (marks); Now for this query: SELECT name, marks FROM marks WHERE name = 'Chinu'; ➡️ Index Only Scan - Required data is already present inside the index - No need to access the main table (heap) - Eliminates extra lookups 💡 What actually changed? - The data didn’t change. - The query didn’t change. 👉 The data access strategy changed. ❌ Sequential Scan → “Check everything” ✅ Index Scan → “Navigate intelligently” 🚀 Index Only Scan → “Don’t even touch the table” ⚠️ Trade-offs Indexes are powerful, but not free: - Additional storage overhead - Slower INSERT / UPDATE operations - Must be designed based on query patterns 📌 Final thought “Indexes don’t just make queries faster — they change how databases think about data access.” Exploring more around execution plans, query optimization, and database internals. #SQL #BackendDevelopment #Database #Performance #LearningInPublic #Developers

To view or add a comment, sign in

Explore content categories