એક ઇન્ડેક્સ એક ડેટા સ્ટ્રક્ચર છે (સામાન્યતः એક B-tree) જે ડેટાબેસને સમગ્ર કોષ્ટક સ્કેન કર્યા વિના પંક્તિઓ ઝડપથી શોધવા દે છે — પુસ્તકના ઇન્ડેક્સ જેવું. તે ઇન્ડેક્સ કરેલી કોલમ(ઓ) પર લુકઅપ્સ, ફિલ્ટર્સ, જોઈનો અને સોર્ટ્સને નાટકીય રીતે ઝડપ આપે છે, પરંતુ વધારાના સંગ્રહ અને ધીમા લખતાવલીના ખર્ચે.\n\n## ઇન્ડેક્સ કેવી રીતે મદદ કરે છે\n\n```sql -- without an index on email, this scans EVERY row (slow on a big table) — O(n) SELECT * FROM users WHERE email = '[email protected]';
-- create an index → the database can find the row directly — O(log n) CREATE INDEX idx_users_email ON users(email); -- now the same query uses the index → dramatically faster text ✓ Columns in WHERE clauses (frequently filtered) ✓ Columns used in JOINs (foreign keys especially) ✓ Columns in ORDER BY (sorting can use the index) ✓ Columns with high SELECTIVITY (many distinct values — email, id) ✓ Primary keys (auto-indexed) and unique constraints text ✗ Columns rarely queried — wasted storage and write overhead ✗ Small tables — a full scan is already fast; an index adds no benefit ✗ Low-selectivity columns (e.g. a boolean with 2 values) — index barely helps ✗ Write-heavy columns — EVERY INSERT/UPDATE/DELETE must also update the indexes → too many indexes SLOW DOWN writes significantly sql CREATE INDEX idx_users_country_name ON users(country, name); -- COMPOSITE (multi-column) -- helps WHERE country = ? AND name = ?, and WHERE country = ? (leftmost prefix) -- but NOT WHERE name = ? alone (order matters!)
