DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workkloads.

Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Recovering an MS SQL Database From Suspect Mode: Step-By-Step Guide
  • SQL Query Performance Tuning in MySQL
  • How to Move System Databases to Different Locations in SQL Server on Linux
  • SQL Commands: A Brief Guide

Trending

  • How to Format Articles for DZone
  • Scalable System Design: Core Concepts for Building Reliable Software
  • Enhancing Security With ZTNA in Hybrid and Multi-Cloud Deployments
  • Fixing Common Oracle Database Problems
  1. DZone
  2. Data Engineering
  3. Databases
  4. How to Reorganize and Rebuild Indexes in MS SQL?

How to Reorganize and Rebuild Indexes in MS SQL?

In this article, we'll explore how to reorganize and rebuild indexes in MS SQL Server to address fragmentation and improve database performance.

By 
Priyanka Chauhan user avatar
Priyanka Chauhan
·
Feb. 12, 25 · Tutorial
Likes (1)
Comment
Save
Tweet
Share
3.4K Views

Join the DZone community and get the full member experience.

Join For Free

Indexes are the objects of MS SQL database files. These schema objects act like a table of contents of the database. These are used to improve the data retrieval operations on an MS SQL database table. 

However, with time, the table can get fragmented due to continuous INSERT and UPDATE operations. Also, like other objects, indexes are also prone to corruption. If the indexes get corrupted, you can receive errors like:

Plain Text
 
Table error: table 'Items' (ID 1954106002). Data row does not have a matching index row in the index 'IX_Advertise_BrandCopy_Price_Stock' (ID 69). Possible missing or invalid keys for the index row matching:

Msg 8955, Level 16, State 1, Line 1

Data row (1:11226494:9) identified by (Id = 11078215) with index values 'AdvertiseFlag = 1 and BrandCopyParentId = 0 and NSFPPrice = 137.50 and NSFPQtyInStock = 0 and Id = 11078215'.

Msg 8951, Level 16, State 1, Line 1


To resolve the errors associated with corruption in indexes or when the fragmentation level of the indexes increases, you can rebuild or reorganize the indexes. In this article, we'll discuss how to reorganize and rebuild the indexes in MS SQL Server. We'll also mention an advanced MS SQL database repair tool that can restore indexes and other objects from corrupted SQL database files quickly with complete precision.

Check the Fragmentation Percentage of Indexes

Before reorganizing the indexes, you need to know the percentage of fragmentation. You can use the below command to check the percentage of the index fragmentation:

SQL
 
SELECT 
    OBJECT_NAME(object_id) tableName12,
    index_id,
    index_type_desc,
    avg_fragmentation_in_percent,
    page_count
FROM 
    sys.dm_db_index_physical_stats (
        DB_ID('Adventureworks2019'), 
        OBJECT_ID('[Person].[Person]'), 
        NULL, NULL, 'DETAILED'
    );


Reorganizing Indexes in SQL Server

If the fragmentation level of the index is between 10 and 30, it is recommended to reorganize the index. You can use the following code in T-SQL to reorganize the index:

SQL
 
ALTER INDEX [PK_Person_BusinessEntityID] ON [Person].[Person]
REORGANIZE;


Alternatively, you can use the SQL Server Management Studio (SSMS) to reorganize the indexes. Follow the below steps:

  • In SSMS, connect to your SQL Server instance.
  • In Object Explorer, expand the database.
  • Expand the Tables folder and then the Indexes folder.
  • Right-click on the index you need to reorganize, and then click Reorganize.

Rebuilding Indexes in MS SQL

If the fragmentation is higher, then you can rebuild the indexes. You can use the DBCC DBREINDEX command to rebuild an index. Here’s how to execute this command:

SQL
 
DBCC DBREINDEX
(
    table_name
    [ , index_name [ , fillfactor ] ]
)
    [ WITH NO_INFOMSGS ]


This command does not support spatial indexes and memory-optimized column store indexes. 

Alternatively, you can use the ALTER INDEX command:

SQL
 
ALTER INDEX [PK_Person_BusinessEntityID] ON [Person].[Person]
REBUILD;


You can also rebuild the indexes by using the graphical user interface in SSMS. Here are the steps:

  • In SSMS, in Object Explorer, expand the database containing the table on which you need to rebuild an index.
  • Expand the Tables folder and then the table on which you need to rebuild an index.
  • Expand the Indexes folder, right-click the index you need to rebuild, and select Rebuild.

Repair the SQL Server Database

If reorganizing or rebuilding the indexes does not work, then you can try the DBCC CHECKDB command with the REPAIR_ALLOW_DATA_LOSS option to repair the database. Here’s how to use this command:

First, change the mode of the database to SINGLE_USER by using the below command:

SQL
 
ALTER DATABASE BusinessEntity SET SINGLE_USER


Next, run the DBCC CHECKDB command as given below to repair the database:

SQL
 
DBCC CHECKDB (N ’BusinessEntity’, REPAIR_ALLOW_DATA_LOSS) WITH ALL_ERRORMSGS, NO_INFOMSGS; 
GO


After repair, set the database mode to MULTI_USER by executing the below command:

SQL
 
ALTER DATABASE BusinessEntity SET MULTI_USER


The above DBCC CHECKDB command can help you resolve all the errors that are related to corruption in indexes. It can repair both clustered and non-clustered indexes in SQL databases. However, it does not guarantee complete data recovery and can result in data loss. To prevent data loss, you can use any professional MS SQL repair tools. They are designed with advanced algorithms to recover all the objects, including clustered and non-clustered indexes, stored procedures, triggers, etc., from the corrupt database. 

Conclusion

You can reduce index fragmentation by reorganizing or rebuilding the index. In this article, we have explained how to check the fragmentation percentage in indexes and how to rebuild the indexes. 

Command (computing) sql Database index

Opinions expressed by DZone contributors are their own.

Related

  • Recovering an MS SQL Database From Suspect Mode: Step-By-Step Guide
  • SQL Query Performance Tuning in MySQL
  • How to Move System Databases to Different Locations in SQL Server on Linux
  • SQL Commands: A Brief Guide

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!