Home >> FAQs/Tutorials >> SQL Server FAQ

SQL Server FAQ - "ALTER INDEX ... REBUILD" - Defragmenting Indexes

By: FYIcenter.com

(Continued from previous topic...)

How To Rebuild Indexes with ALTER INDEX ... REBUILD?

When an index is defragmented to a large percentage, like > 30%, you can use the "ALTER INDEX ... REBUILD" statement to rebuild the index. Here is a tutorial exercise on rebuilding indexes:

USE FyiCenterData;
GO

UPDATE fyi_links_indexed SET url = REVERSE(url)
   WHERE id <=50000;
GO
(50000 row(s) affected)

SELECT i.index_id, i.name, s.avg_fragmentation_in_percent
   FROM sys.dm_db_index_physical_stats (
      DB_ID(N'FyiCenterData'), 
      OBJECT_ID(N'fyi_links_indexed'),
      DEFAULT, DEFAULT, DEFAULT) s, sys.indexes i
   WHERE s.object_id = i.object_id
      AND s.index_id = i.index_id;
GO
0        NULL             0.574712643678161
2        fyi_links_url    85.0142045454545
3        fyi_links_counts 0.448430493273543

ALTER INDEX fyi_links_url ON fyi_links_indexed REBUILD;
GO

SELECT i.index_id, i.name, s.avg_fragmentation_in_percent
   FROM sys.dm_db_index_physical_stats (
      DB_ID(N'FyiCenterData'), 
      OBJECT_ID(N'fyi_links_indexed'),
      DEFAULT, DEFAULT, DEFAULT) s, sys.indexes i
   WHERE s.object_id = i.object_id
      AND s.index_id = i.index_id;
GO
0        NULL             0.574712643678161
2        fyi_links_url    0
3        fyi_links_counts 0.448430493273543

Rebuilding an index brings the fragmentation level to 0% in this case.

(Continued on next topic...)

  1. What Are Indexes?
  2. How To Create an Index on an Existing Table?
  3. How To View Existing Indexes on an Given Table using SP_HELP?
  4. How To View Existing Indexes on an Given Table using sys.indexes?
  5. How To Drop Existing Indexes?
  6. Is the PRIMARY KEY Column of a Table an Index?
  7. Does the UNIQUE Constraint Create an Index?
  8. What Is the Difference Between Clustered and Non-Clustered Indexes?
  9. How To Create a Clustered Index?
  10. How To Create an Index for Multiple Columns?
  11. How To Create a Large Table with Random Data for Index Testing?
  12. How To Measure Performance of INSERT Statements?
  13. Does Index Slows Down INSERT Statements?
  14. Does Index Speed Up SELECT Statements?
  15. What Happens If You Add a New Index to Large Table?
  16. What Is the Impact on Other User Sessions When Creating Indexes?
  17. What Is Index Fragmentation?
  18. What Causes Index Fragmentation?
  19. How To Defragment Table Indexes?
  20. How To Defragment Indexes with ALTER INDEX ... REORGANIZE?
  21. How To Rebuild Indexes with ALTER INDEX ... REBUILD?
  22. How To Rebuild All Indexes on a Single Table?
  23. How To Recreate an Existing Index?

Related Articles:

More...


Other Tutorials/FAQs:

More...


Related Resources:

More...


Selected Jobs:

More...