Reference · Database · SQL Server

Index: clustered, non-clustered, composite, covering

Ringkasan satu halaman. Dari Lesson 0022. Skrip lab: dotnet/lab/0022-index.sql.

Clustered vs non-clustered [2]

ClusteredNon-clustered
Analogibuku telepon: isinya sendiri urutindeks di belakang buku → nomor halaman
Leafdata pages, semua kolomkey + row locator (+ kolom INCLUDE)
Per tabel1banyak
Row locator—clustered key (heap: RID)
Default dariPRIMARY KEYUNIQUE, CREATE INDEX

Membaca plan [3]

OperatorArtinya
Clustered Index Scanbaca seluruh tabel
Index Seeklompat langsung ke rentang key
Key Lookup (+ Nested Loops)ambil kolom yang tidak ada di index dari clustered index, sekali per baris
RID Lookupsama, untuk heap
Sorturutan index tidak cocok dengan ORDER BY

Banyak baris × key lookup > satu scan → optimizer memilih scan (tipping point). Obatnya covering index.

Covering + composite [1] [7]

-- SELECT Name, Price FROM dbo.Product WHERE CategoryId = @c ORDER BY Price DESC
CREATE INDEX IX_Product_CategoryId_Price
    ON dbo.Product (CategoryId, Price DESC)   -- equality dulu, lalu range/ORDER BY
    INCLUDE (Name);                           -- hanya diambil → INCLUDE
-- Id tidak perlu: clustered key otomatis ikut

Kapan index merugikan [1]

Mengukur [4] [5]

SET STATISTICS IO, TIME ON;
-- query sebelum index → CREATE INDEX → query yang sama lagi
SET STATISTICS IO, TIME OFF;

Bandingkan logical reads (page dari cache, 1 page = 8 KiB [6]), bukan milidetik. Lihat juga actual execution plan.

Jawaban 60–90 detik

Clustered index = tabelnya sendiri, urut menurut key, satu per tabel, default dari PK (idealnya int IDENTITY). Non-clustered = struktur terpisah berisi key + clustered key sebagai penunjuk; kolom lain diambil lewat key lookup. Untuk query lambat: ukur logical reads + plan, buat composite index equality dulu lalu kolom ORDER BY, kolom yang hanya diambil di INCLUDE (covering, tanpa key lookup), ukur lagi. Risiko: biaya tulis dan storage; jangan index spekulatif, jangan index kolom berselektivitas rendah, hapus yang tak terpakai.

Sumber: [1] Index architecture and design guide · [2] Clustered and nonclustered indexes described · [3] Showplan operators · [4] SET STATISTICS IO · [5] SET STATISTICS TIME · [6] Pages and extents · [7] CREATE INDEX