In one of my previous articles, I talked about Index Fragmentation in SQL Server in terms of how to track it and how to resolve it. In this post, we are going to see how to rebuild all the indexes of a database in SQL Server.
The techniques explained in that post provided ways of reorganizing/rebuilding specific indexes or all the indexes within a given table. But what about when the DBA needs to rebuild all the indexes within a database? How can he achieve this?
It is a fact that in some cases where a large amount of indexes in a database on SQL Server has a large percentage of fragmentation, then the recommended approach is to rebuild those indexes. To this end, in the worst scenario, the DBA will need to rebuild the indexes in all the tables of the database.
My previous post on the topic explained ways of rebuilding specific or all the indexes within a table.
Under normal circumstances there is not a direct way allowing to rebuild all the indexes of a database with a single command. A workaround is to run different rebuild statements for each table.
Though, I know that workarounds are not very desirable in many cases as they might demand a large amount of time 🙂
There is not need to worry 🙂 In SQL Server there is the undocumented stored procedure sp_MSforeachtable which allows for recursively executing a T-SQL statement (or more) for all the tables within a database with the use of a single line of code.
Learn more tips like this! Check our online course!
Learn essential hands-on SQL Server Administration tips on SQL Server maintenance, security, performance, integration, error handling and more. Many live demonstrations and downloadable resources included!
(Lifetime access, Q&A, certificate of completion).
Below I propose the syntax on how to rebuild all the indexes of a given database by utilizing the sp_MSforeachtable stored procedure.
SQL Server 2000:
--Rebuild all indexes with keeping the default fill factor for each index
USE [DATABASE_NAME]
EXEC sp_MSforeachtable @command1="print '?' DBCC DBREINDEX ('?')"
--Rebuild all indexes with specifying the fill factor
USE [DATABASE_NAME]
EXEC sp_MSforeachtable @command1="print '?' DBCC DBREINDEX ('?', ' ', [FILL_FACTOR_PERC])"
SQL Server 2005 or later:
You can either use the syntax provided above for SQL Server 2000 or:
--Rebuild all indexes online with keeping the default fill factor for each index
USE [DATABASE_NAME]
EXEC sp_MSforeachtable @command1="print '?'", @command2="ALTER INDEX ALL ON ? REBUILD WITH (ONLINE=ON)"
--Rebuild all indexes offline with keeping the default fill factor for each index
USE [DATABASE_NAME]
EXEC sp_MSforeachtable @command1="print '?'", @command2="ALTER INDEX ALL ON ? REBUILD WITH (ONLINE=OFF)"
--Rebuild all indexes online with specifying the fill factor
USE [DATABASE_NAME]
EXEC sp_MSforeachtable @command1="print '?'", @command2="ALTER INDEX ALL ON ? REBUILD WITH (FILLFACTOR=[FILL_FACTOR_PERC],ONLINE=ON)"
--Rebuild all indexes offline with specifying the fill factor
USE [DATABASE_NAME]
EXEC sp_MSforeachtable @command1="print '?'", @command2="ALTER INDEX ALL ON ? REBUILD WITH (FILLFACTOR=[FILL_FACTOR_PERC],ONLINE=OFF)"
Artemakis Artemiou is a seasoned Senior Database and AI/Automation Architect with over 20 years of expertise in the IT industry. As a Certified Database, Cloud, and AI professional, he has been recognized as a thought leader, earning the prestigious Microsoft Data Platform MVP title for nine consecutive years (2009-2018). Driven by a passion for simplifying complex topics, Artemakis shares his expertise through articles, online courses, and speaking engagements. He empowers professionals around the globe to excel in Databases, Cloud, AI, Automation, and Software Development. Committed to innovation and education, Artemakis strives to make technology accessible and impactful for everyone.
Views:18,440
2 thoughts on “How to rebuild all the indexes of a database in SQL Server”
thank you very much and i am new for DBA so i need to rebuil the indes for whole database so which is the better way means offline or online ???
Hi Suresh,
When you rebuild indexes Online, the underlying tables and associated indexes are available for queries and data modification during the index operation. However, please note that there are some requirements/restrictions when using this feature. For example, the Online Indexing feature is only available in the Enterprise edition of SQL server. Also, up to SQL Server 2008 R2, you could not perform online rebuild on Large Object (LOB) data: varchar(max), nvarchar(max), varbinary(max), or XML. From SQL Server 2012 Enteprise and later there is not such restriction.
When you rebuild indexes Offline, the operation acquires a Schema modification (Sch-M) lock on the table. This prevents all user access to the underlying table for the duration of the operation.
Online index rebuild is a more "convenient" option but before planning to do so you need to check all the prerequisites and guidelines (links provided below) in order to ensure that you can use this feature.
In the opposite case (offline index rebuild), you will have to take into consideration that there will be downtime for each table during the offline rebuild process of its indexes.
For more info you can check out the following MSDN library articles:
We use cookies on our website to give you the most relevant experience by remembering your preferences and repeat visits. By clicking “Accept All”, you consent to the use of ALL the cookies. However, you may visit "Cookie Settings" to provide a controlled consent. Read More
This website uses cookies to improve your experience while you navigate through the website. Out of these, the cookies that are categorized as necessary are stored on your browser as they are essential for the working of basic functionalities of the website. We also use third-party cookies that help us analyze and understand how you use this website. These cookies will be stored in your browser only with your consent. You also have the option to opt-out of these cookies. But opting out of some of these cookies may affect your browsing experience.
Necessary cookies are absolutely essential for the website to function properly. These cookies ensure basic functionalities and security features of the website, anonymously.
Cookie
Duration
Description
cookielawinfo-checkbox-analytics
11 months
This cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Analytics".
cookielawinfo-checkbox-functional
11 months
The cookie is set by GDPR cookie consent to record the user consent for the cookies in the category "Functional".
cookielawinfo-checkbox-necessary
11 months
This cookie is set by GDPR Cookie Consent plugin. The cookies is used to store the user consent for the cookies in the category "Necessary".
cookielawinfo-checkbox-others
11 months
This cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Other.
cookielawinfo-checkbox-performance
11 months
This cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Performance".
viewed_cookie_policy
11 months
The cookie is set by the GDPR Cookie Consent plugin and is used to store whether or not user has consented to the use of cookies. It does not store any personal data.
Functional cookies help to perform certain functionalities like sharing the content of the website on social media platforms, collect feedbacks, and other third-party features.
Performance cookies are used to understand and analyze the key performance indexes of the website which helps in delivering a better user experience for the visitors.
Analytical cookies are used to understand how visitors interact with the website. These cookies help provide information on metrics the number of visitors, bounce rate, traffic source, etc.
Advertisement cookies are used to provide visitors with relevant ads and marketing campaigns. These cookies track visitors across websites and collect information to provide customized ads.
thank you very much and i am new for DBA so i need to rebuil the indes for whole database so which is the better way means offline or online ???
Hi Suresh,
When you rebuild indexes Online, the underlying tables and associated indexes are available for queries and data modification during the index operation. However, please note that there are some requirements/restrictions when using this feature. For example, the Online Indexing feature is only available in the Enterprise edition of SQL server. Also, up to SQL Server 2008 R2, you could not perform online rebuild on Large Object (LOB) data: varchar(max), nvarchar(max), varbinary(max), or XML. From SQL Server 2012 Enteprise and later there is not such restriction.
When you rebuild indexes Offline, the operation acquires a Schema modification (Sch-M) lock on the table. This prevents all user access to the underlying table for the duration of the operation.
Online index rebuild is a more "convenient" option but before planning to do so you need to check all the prerequisites and guidelines (links provided below) in order to ensure that you can use this feature.
In the opposite case (offline index rebuild), you will have to take into consideration that there will be downtime for each table during the offline rebuild process of its indexes.
For more info you can check out the following MSDN library articles:
Guidelines for Online Index Operations
How Online Index Operations Work
Features Supported by the Editions of SQL Server 2014