# My SQL Server appears to be running slowly. What is SQL Server index fragmentation and how do I fix it?

**URL:** <https://discuss.workflowgen.com/t/my-sql-server-appears-to-be-running-slowly-what-is-sql-server-index-fragmentation-and-how-do-i-fix-it/408>\
**Category:** Performance\
**Created:** [July 27, 2016, 2:27am UTC](https://discuss.workflowgen.com/t/my-sql-server-appears-to-be-running-slowly-what-is-sql-server-index-fragmentation-and-how-do-i-fix-it/408 "2016-07-27T02:27:00Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![wfg-admin](https://yyz2.discourse-cdn.com/flex030/user_avatar/discuss.workflowgen.com/wfg-admin/32/714_2.png) [@wfg-admin](https://discuss.workflowgen.com/u/wfg-admin)\
**Post date:** [July 27, 2016, 2:27am UTC](https://discuss.workflowgen.com/t/my-sql-server-appears-to-be-running-slowly-what-is-sql-server-index-fragmentation-and-how-do-i-fix-it/408/1 "2016-07-27T02:27:00Z")

</div>

## Issue

My SQL Server appears to be running slowly. What is SQL Server index fragmentation, and how do I fix it?

## Background

See the [Reorganize and Rebuild Indexes](https://msdn.microsoft.com/en-us/library/ms189858(v=sql.130).aspx) MSDN article for information on index fragmentation (choose your version of SQL Server from the drop-down menu).

## Solutions

There are two solutions to this issue.

### Solution 1

Run either the Rebuild or Reorganize commands then verify if your WorkflowGen indexes have been successfully following the instructions in the above article.

### Solution 2

Set up a scheduled defragmentation by scheduling a job to run the defragmentation script.

For instructions on how to schedule a job, see the [How to: Schedule a Job (SQL Server Management Studio)](https://technet.microsoft.com/en-us/library/ms191439(v=sql.120).aspx) MSDN article (choose your version of SQL Server from the drop-down list).

Run the **B. Using DBCC SHOWCONTIG and DBCC INDEXDEFRAG to defragment the indexes in a database** sample script in the [DBCC INDEXDEFRAG (Transact-SQL)](https://msdn.microsoft.com/en-ca/library/ms177571(v=sql.110).aspx) MSDN article. (The script can be run as-is.)

### Script example

```sql
DECLARE @TableName nvarchar(255),
        @SqlQuery nvarchar(max) 

SELECT @TableName = min(TABLE_NAME) FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE='BASE TABLE'

WHILE @TableName is not null
BEGIN
    SET @SqlQuery='ALTER INDEX ALL ON [' + @TableName + '] REORGANIZE;'
    EXEC SP_EXECUTESQL @SqlQuery
    SELECT @TableName = min(TABLE_NAME) FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE='BASE TABLE' and TABLE_NAME > @TableName          
END

```
