Have you ever noticed your SQL Server getting slow over time? Queries taking longer than before?
Just like cleaning up your room helps you find things faster, cleaning up your database indexes can help your server respond quicker.
If your SQL Server database is getting slower, it could be due to something called index fragmentation. In this post, we’ll explain what that means, why it affects performance, and how to fix it using index reorganization and index rebuilding.
🧠 What Are Indexes in SQL Server?
Think of an index like the table of contents in a book.
If you want to find “Chapter 5,” you don’t read every page — you use the index.
The same thing happens in SQL Server. It uses indexes to find your data faster.
Without indexes (or with messy ones), SQL has to search every row — which is slow, especially with millions of records!
⚠️ Why Indexes Get Fragmented
Over time, as you insert, update, or delete data in a database table, the physical order of data pages may no longer match the logical order defined by the index.
This is known as fragmentation, and it can negatively impact query performance.
Example:
Logical order (ideal): 1 2 3 4 5 6
Physical order (actual): 6 2 3 5 4 1
This mismatch is called fragmentation — the data is scattered instead of being stored in order.
This happens because when rows are inserted, updated, or deleted, the database engine might not find space in the ideal location,
so it stores the data wherever it can. Over time, this leads to pages being stored out of order.
📊 Fragmentation Levels and What to Do
Action | Description | Use When Fragmentation Is | Locks Table | Performance Impact |
---|---|---|---|---|
None | Index is healthy; no action needed | 0% – 5% | ❌ No | ● None |
Reorganize | Light defrag; reshuffles leaf-level pages only | 5% – 30% | ❌ No | ●●● Low |
Rebuild | Drops and recreates the index entirely | >30% | ✅ Yes (Standard Edition) ✅ Optional Online in Enterprise | ●● High |
🔍 How to Check Fragmentation in SQL Server
Run the script below in your preferred SQL query tool (SSMS, Azure Data Studio, DBeaver, etc.). Replace AdventureWorks2022
with your database name.
USE AdventureWorks2022;
GO
SELECT
dbschemas.[name] AS SchemaName,
dbtables.[name] AS TableName,
dbindexes.[name] AS IndexName,
indexstats.avg_fragmentation_in_percent AS [Fragmentation (%)],
CASE
WHEN indexstats.avg_fragmentation_in_percent > 30
THEN 'REBUILD'
WHEN indexstats.avg_fragmentation_in_percent > 5
THEN 'REORGANIZE'
ELSE 'NO ACTION'
END AS MaintenanceAction
FROM
sys.dm_db_index_physical_stats(DB_ID(), NULL, NULL, NULL, 'LIMITED') AS indexstats
INNER JOIN sys.tables dbtables
ON dbtables.[object_id] = indexstats.[object_id]
INNER JOIN sys.schemas dbschemas
ON dbtables.[schema_id] = dbschemas.[schema_id]
INNER JOIN sys.indexes AS dbindexes
ON dbindexes.[object_id] = indexstats.[object_id]
AND indexstats.index_id = dbindexes.index_id
WHERE
indexstats.database_id = DB_ID()
AND dbindexes.name IS NOT NULL ORDER BY
indexstats.avg_fragmentation_in_percent DESC;
Code language: PHP (php)

🔁 How to Reorganize or Rebuild Indexes
Once you know the fragmentation level, you can either reorganize or rebuild. Here’s how:
✅ Reorganize Index (for 5% – 30% fragmentation)
ALTER INDEX ALL ON dbo.YourTableName
REORGANIZE;
Code language: CSS (css)
- Safe to run during business hours
- Does not lock the table
🔄 Rebuild Index (for over 30% fragmentation)
ALTER INDEX ALL ON dbo.YourTableName
REBUILD;
Code language: CSS (css)
- Best done during off-peak hours
- Can temporarily lock the table in Standard Edition
🛠️ Rebuild or Reorganize All Indexes in the Database
Rebuild All Indexes
USE YourDatabaseName;
GO
EXEC sp_MSforeachtable
@command1="PRINT 'Rebuilding Indexes on ?'; ALTER INDEX ALL ON ? REBUILD;";
Code language: CSS (css)
Reorganize All Indexes
USE YourDatabaseName;
GO
EXEC sp_MSforeachtable
@command1="PRINT 'Reorganizing Indexes on ?'; ALTER INDEX ALL ON ? REORGANIZE;";
Code language: CSS (css)
❓ Will This Modify My Data?
Nope! ✅
Neither REORGANIZE
nor REBUILD
changes the actual data values in your tables.
It only restructures how SQL Server stores and accesses them for better performance.
📅 Best Practices for Index Maintenance
- 🗓️ Schedule weekly or monthly index maintenance.
- ⚠️ Run
REBUILD
jobs during low-traffic hours to reduce lock contention. - 💡 Use SQL Server Agent to automate index optimization tasks.
🧩 Bonus Tip: Automate It with a SQL Agent Job
What is SQL Server Agent?
A built-in service to schedule and automate tasks like backups, integrity checks, and index maintenance.
Why Automate?
- Ensure consistent, regular index maintenance
- Reduce human error
- Maintain stable query performance
- Run jobs during off-peak hours
- Scale maintenance across databases
How to Set Up an Index Maintenance Job
- Open SSMS and connect to your server.
- Create a new job under SQL Server Agent > Jobs > New Job.
- Name the job, e.g., “Weekly Index Maintenance”.
- Add a step: Use T-SQL to rebuild or reorganize indexes:
EXEC sp_MSforeachtable 'ALTER INDEX ALL ON ? REBUILD WITH (ONLINE = ON)';
- Schedule the job to run during low-traffic times (e.g., Sundays at 2 AM).
- Optionally, configure notifications for job success or failure alerts.
- Save and enable the job.
🏁 Conclusion
Index fragmentation is a silent killer of SQL Server performance. By learning the difference betweenREORGANIZE
and REBUILD
, and applying the right strategy, you’ll keep your database
running smoothly and your queries blazing fast. ⚡
🙋 Need Help Optimizing Your Database?
Our team of experts can help you audit and tune your SQL Server environment for peak performance.
Experience the iXora Solution difference as your trusted offshore software development partner. We’re here to empower your vision with dedicated, extended, and remote software development teams. Our agile processes and tailored software development services optimize your projects, ensuring efficiency and success. At iXora Solution, we thrive in a dynamic team culture and experience innovation in the field of custom-made software development.
Have specific project requirements? Personalized or customized software solutions! You can contact iXora Solution expert teams for any consultation or coordination from here. We are committed to maximizing your business growth with our expertise as a custom software development and offshore solutions provider. Let’s make your goals a reality.
Thanks for your patience!
Add a Comment