Indexes CHỈ MỤC DỮ LiỆU
Creating Index or not ? Creating index Donot creating index Speeds up data access Enforces uniqueness of rows Donot creating index Consumes disk space Incurs overhead Primary and foreign keys Frequently searched in ranges Frequently accessed in sorted order Seldom referenced in queries Containing few unique values Defined with bit, text, or image data types
Creating Index Using the CREATE INDEX Statement USE library CREATE CLUSTERED INDEX cl_lastname ON library..member (lastname)
Creating Unique Indexes USE library CREATE UNIQUE INDEX title_ident ON title (title_no) 12 Le Petit Prince Antoine de Saint-Exupery ~ ~ ~ Duplicate key values are not allowed when a new row is added to the table title title_no author synopsis 10 11 The Night-Born Lemon Walking Jack London Motojirou Henry David Thoreau
Creating Composite Indexes USE library CREATE UNIQUE INDEX loan_ident ON loan (isbn, copy_no) loan isbn copy_no title_no member_no 342 343 5 10 4 35 3744 5278 3445 out_date 1998-01-06 1998-01-04 Column 1 Column 2 Composite Key
Truy vấn không có index use AdventureWorks SELECT * INTO Sales.Customer_NoIndex FROM Sales.Customer SELECT CustomerID, CustomerType FROM Sales.Customer_NoIndex WHERE CustomerID = 11001
Truy vấn có index SELECT CustomerID, CustomerType FROM Sales.Customer_Index WHERE CustomerID = 11001 SELECT * INTO Sales.Customer_Index FROM Sales.Customer GO CREATE INDEX Idx_CustomerID ON Sales.Customer_Index(CustomerID)
SELECT CustomerID, CustomerType FROM Sales SELECT CustomerID, CustomerType FROM Sales.Customer_NoIndex WHERE CustomerID = 11001 FROM Sales.Customer_Index
2 loại indexes Clustered Indexes Non-clustered Indexes The physical row order of the table and the order of rows in the index are the same Each table can have only one clustered index Non-clustered Indexes Non-clustered indexes are the SQL server default Existing non-clustered indexes are automatically rebuilt when: An existing clustered index is dropped A clustered index is created The DROP_EXISTING option is used to change which columns define the clustered index