๐ ์ธ๋ฑ์ค(Index)๋?
๐ Clustered Index vs Non-Clustered Index ์ฐจ์ด์
| ๊ตฌ๋ถ | Clustered Index (ํด๋ฌ์คํฐ๋ ์ธ๋ฑ์ค) | Non-Clustered Index (๋ ผํด๋ฌ์คํฐ๋ ์ธ๋ฑ์ค) |
|---|---|---|
| ๊ฐ๋ | ์ค์ ๋ฐ์ดํฐ๊ฐ ์ธ๋ฑ์ค ์์ฒด์ ์ ์ฅ | ์ธ๋ฑ์ค์ ๋ฐ์ดํฐ๊ฐ ๋ถ๋ฆฌ๋์ด ์์ |
| ๋ฐ์ดํฐ ์ ๋ ฌ | ๋ฐ์ดํฐ ์์ฒด๊ฐ ํค ๊ฐ์ ๋ฐ๋ผ ์ ๋ ฌ๋จ | ๋ฐ์ดํฐ๋ ์ ๋ ฌ๋์ง ์๊ณ , ์ธ๋ฑ์ค๋ง ๋ณ๋๋ก ๊ด๋ฆฌ |
| ์ ์ฅ ๊ตฌ์กฐ | Leaf Page = Data Page (์ค์ ๋ฐ์ดํฐ ํฌํจ) | Leaf Page = Index Page (๋ฐ์ดํฐ ์ฃผ์ ํฌํจ) |
| ๊ฐ์ | ํ ์ด๋ธ๋น 1๊ฐ๋ง ๊ฐ๋ฅ | ํ ์ด๋ธ๋น ์ฌ๋ฌ ๊ฐ ๊ฐ๋ฅ |
| ๊ฒ์ ์๋ | ๋ฐ์ดํฐ๊ฐ ์ ๋ ฌ๋์ด ์์ด์ ๊ฒ์์ด ๋น ๋ฆ | ์ถ๊ฐ์ ์ธ Lookup์ด ํ์ํ์ฌ ์๋๊ฐ ๋๋ฆด ์ ์์ |
| ์ฌ์ฉ ์ | PRIMARY KEY | WHERE ์กฐ๊ฑด์ด ์์ฃผ ์ฌ์ฉ๋๋ ์ปฌ๋ผ |
๐ ์ค์ต ๋ฐ์ดํฐ๋ฒ ์ด์ค: Northwind
โ ํ์ฌ ๋ฐ์ดํฐ๋ฒ ์ด์ค ์ ๋ณด ํ์ธ
-- Northwind ๋ฐ์ดํฐ๋ฒ ์ด์ค ์ ๋ณด ํ์ธ
EXEC sp_helpdb 'Northwind';
โ
์ฃผ๋ฌธ ์์ธ ์ ๋ณด ํ
์ด๋ธ(Order Details) ์กฐํ
-- ์ฃผ๋ฌธ ์์ธ ์ ๋ณด ์กฐํ
SELECT *
FROM [Order Details]
ORDER BY OrderID;
โ ํ ์คํธ์ฉ ํ ์ด๋ธ ์์ฑ ๋ฐ ๋ฐ์ดํฐ ๋ณต์ฌ
-- ์์ ํ
์คํธ ํ
์ด๋ธ ์์ฑ
SELECT *
INTO TestOrderDetails
FROM [Order Details];
-- ๋ฐ์ดํฐ ํ์ธ
SELECT * FROM TestOrderDetails;
๐ Non-Clustered Index ์์ฑ
-- Non-Clustered ์ธ๋ฑ์ค ์ถ๊ฐ
CREATE INDEX Index_OrderDetails
ON TestOrderDetails(OrderID, ProductID);
โ ์ธ๋ฑ์ค ์ ๋ณด ํ์ธ
EXEC sp_helpindex 'TestOrderDetails';
โ ์ธ๋ฑ์ค ๋ฒํธ ์ฐพ๊ธฐ
SELECT index_id, name
FROM sys.indexes
WHERE object_id = object_id('TestOrderDetails');
๐น ์ถ๋ ฅ ์์
| index_id | name |
|----------|----------------------|
| 2 | Index_OrderDetails |
๐ ์ธ๋ฑ์ค ์ ๋ณด ์กฐํ
DBCC IND('Northwind', 'TestOrderDetails', 2);
๐ Non-Clustered Index์ B-Tree ๊ตฌ์กฐ ์์
[ Root: 904 ]
/ \
[832] [872] [873] [874] [875] [876]
โ ํน์ ํ์ด์ง ์์ธ ์กฐํ
DBCC PAGE('Northwind', 1, 832, 3);
๐ Heap Table๊ณผ Non-Clustered Index
๐ Clustered Index ์์ฑ
-- Clustered Index ์ถ๊ฐ
CREATE CLUSTERED INDEX Index_OrderDetails_Clustered
ON TestOrderDetails(OrderID);
โ Clustered Index ์์ฑ ํ ์ธ๋ฑ์ค ์ ๋ณด ํ์ธ
DBCC IND('Northwind', 'TestOrderDetails', 1);
๐ Clustered Index์ B-Tree ๊ตฌ์กฐ ์์
[ Root: 928 ]
/ \
[880] [888] [889] [890] [891] ... [896]
โ ํน์ ํ์ด์ง ์์ธ ์กฐํ
DBCC PAGE('Northwind', 1, 880, 3);
๐ Clustered Index์ ํน์ง
โ Heap Table ๊ธฐ๋ฐ Non-Clustered Index ๊ตฌ์กฐ
[ Non-Clustered Index ]
|
[ Heap Table ] โ ๋ฐ์ดํฐ ์ ์ฅ ์์น (RID ์ฌ์ฉ)
โ Clustered Index ๊ธฐ๋ฐ Non-Clustered Index ๊ตฌ์กฐ
[ Non-Clustered Index ]
|
[ Clustered Index ] โ ๋ฐ์ดํฐ ์ ์ฅ ์์น (Key ์ฌ์ฉ)
๐ Non-Clustered Index๋ Clustered Index ์กด์ฌ ์ฌ๋ถ์ ๋ฐ๋ผ ๋์ ๋ฐฉ์์ด ๋ค๋ฆ
โ Heap Table์ ํตํ ๋ฐ์ดํฐ ์กฐํ
-- Heap Table์ ํตํ ๋ฐ์ดํฐ ์กฐํ (Non-Clustered Index๋ง ์กด์ฌํ ๊ฒฝ์ฐ)
DBCC PAGE('Northwind', 1, 832, 3);
โ Clustered Index ๊ธฐ๋ฐ ๋ฐ์ดํฐ ์กฐํ
-- Clustered Index ๊ธฐ๋ฐ ๋ฐ์ดํฐ ์กฐํ (Non-Clustered + Clustered Index ๋์ ๋ฐฉ์ ํ์ธ)
DBCC PAGE('Northwind', 1, 880, 3);