When your SQL Server database becomes slow, one reason might be that its indexes are fragmented. To improve performance, you can rebuild or reorganize these indexes. Reindexing helps the database run faster by organizing the data more efficiently. In this article, we’ll show you how to use a simple PowerShell script to reindex all databases in SQL Server.

Why Reindexing is Important

SQL Server uses indexes to quickly find data. Over time, these indexes become fragmented, which means that the data is scattered around, making searches slower. Reindexing helps by organizing the data, improving the speed of queries and other database operations.

What You Need Before Starting

  • SQL Server Management Studio (SSMS) installed.
  • SQL Server with a few databases you want to reindex.
  • PowerShell installed (comes pre-installed on Windows).

Step-by-Step Guide to Reindexing with PowerShell

We will now show you a PowerShell script that reindexes all SQL Server databases on a server. Follow the steps below to understand and run this script.

Step 1: Open PowerShell as Administrator

To run the script, you need to open PowerShell with administrator privileges:

  • Click the Start menu, type “PowerShell,” then right-click on it and choose “Run as Administrator.”

Step 2: Install the SqlServer Module

Run the following command to install the SqlServer module from the PowerShell Gallery:


Install-Module -Name SqlServer -AllowClobber

You may be prompted to confirm the installation from an untrusted repository. Type Y and press Enter to proceed.

How to Reindex All SQL Server Databases Using a PowerShell Script General Articles mssql
Install SQL Server module in PowerShell

Step 3: Write or Copy the PowerShell Script

Below is a complete working PowerShell script that connects to your SQL Server instance and reindexes all databases:


# Import the SQL Server module
Import-Module -Name SqlServer

# Define the SQL Server instance name
$serverInstance = "YourSQLServerInstanceName"

# Get the list of all databases
$databases = Invoke-Sqlcmd -ServerInstance $serverInstance -Query "SELECT name FROM sys.databases WHERE state_desc = 'ONLINE' AND name NOT IN ('master', 'tempdb', 'model', 'msdb')"

# Loop through each database and reindex all tables
foreach ($db in $databases) {
$dbName = $db.name
Write-Host "Reindexing database: $dbName"

# Run the reindex script for each database
$query = @"
USE [$dbName];
DECLARE @TableName VARCHAR(255);
DECLARE TableCursor CURSOR FOR
SELECT table_name FROM information_schema.tables WHERE table_type = 'BASE TABLE';
OPEN TableCursor;
FETCH NEXT FROM TableCursor INTO @TableName;
WHILE @@FETCH_STATUS = 0
BEGIN
	PRINT 'Reindexing: '   @TableName;
	EXEC('ALTER INDEX ALL ON ['   @TableName   '] REBUILD');
	FETCH NEXT FROM TableCursor INTO @TableName;
END;
CLOSE TableCursor;
DEALLOCATE TableCursor;
"@

# Execute the query for the current database
Invoke-Sqlcmd -ServerInstance $serverInstance -Database $dbName -Query $query
}

Write-Host "Reindexing complete for all databases."

Step 4: Modify the Script

Before running the script, make sure to replace YourSQLServerInstanceName with your actual SQL Server instance name. You can find this name in SQL Server Management Studio (SSMS) by looking at the “Connect” window when you log in.

Step 5: Run the Script

Once you have copied the script and made the necessary changes, paste it into the PowerShell window and press Enter. The script will connect to your SQL Server, and you will see messages for each database and table that is being reindexed.

How to Reindex All SQL Server Databases Using a PowerShell Script General Articles mssql
Reindex SQL Server Database using PowerShell

Explanation of the PowerShell Script

  • Import-Module -Name SqlServer: This loads the SQL Server module, allowing PowerShell to connect and run SQL commands.
  • Invoke-Sqlcmd: This is the command that lets PowerShell run SQL queries on your SQL Server instance.
  • $databases: This stores the list of all databases that are online and not system databases (like master, tempdb, etc.).
  • foreach ($db in $databases): This loops through each database and performs the reindexing operation.
  • ALTER INDEX ALL ON [TableName] REBUILD: This SQL command rebuilds all the indexes on each table in the database, which improves performance.

Conclusion

By following the steps above, you can easily reindex all your SQL Server databases using PowerShell. This script saves time by automating the reindexing process for multiple databases. Regular reindexing helps keep your databases running smoothly and improves performance, especially for large and frequently used databases.