Chapter 4: Database Optimization

If performance issues arise during operation, you can automatically optimize the database by clicking the “Optimize Database” button on the “Maintenance” screen.

External Optimization

In addition, the following BAT scripts can be used to improve database performance:

SQL Server uses statistics about the distribution of data in tables to determine the fastest way to process queries (which indexes to use, how to join tables, etc.).

When large amounts of data are added, modified, or deleted, these statistics become outdated. Without an update, the database server selects incorrect execution plans, which can significantly slow down the entire system.

When this is recommended:

Regular maintenance (e.g., weekly/nightly): Outside of business hours using the Windows Task Scheduler to maintain stable performance.

After large data imports or deletions: When thousands of records have been added or modified all at once.

In case of performance issues: When the application suddenly responds unusually slowly, even though server load appears normal.

You can automate this using the following BAT script:

@ECHO OFF
:: ============================================================
:: update-statistics.bat -S <Server> [-E | -U <User> -P <Pass>]
:: ============================================================
SETLOCAL

SET SERVER=%~2
IF "%SERVER%"=="" (
    ECHO Usage: %~nx0 -S ^<Server^> [-E ^| -U ^<User^> -P ^<Pass^>]
    EXIT /B 1
)

:: Authentication parameters: all arguments after -S <Server>
SET AUTH=%3 %4 %5 %6 %7
IF "%AUTH: =%"=="" SET AUTH=-E

SET LOG=%~dp0update-statistics_%DATE:/=-%.log

ECHO [%DATE% %TIME%] Start: %SERVER% >> "%LOG%"

sqlcmd -S "%SERVER%" %AUTH% -d "VISTRAX_3_6_MANDATOR_1" -b ^
    -Q "EXEC sp_MSforeachtable 'UPDATE STATISTICS ? WITH FULLSCAN';" >> "%LOG%" 2>&1
IF %ERRORLEVEL% NEQ 0 ECHO [ERROR] VISTRAX_3_6_MANDATOR_1 & GOTO :END

sqlcmd -S "%SERVER%" %AUTH% -d "VISTRAX_3_6" -b ^
    -Q "EXEC sp_MSforeachtable 'UPDATE STATISTICS ? WITH FULLSCAN';" >> "%LOG%" 2>&1
IF %ERRORLEVEL% NEQ 0 ECHO [ERROR] VISTRAX_3_6 & GOTO :END

ECHO [%DATE% %TIME%] Completed successfully. >> "%LOG%"
ECHO Success. Log: %LOG%

:END
ENDLOCAL
EXIT /B %ERRORLEVEL%

The Query Store is a built-in feature of Microsoft SQL Server that functions like a “flight recorder” for databases. It automatically records which SQL queries are executed, how long they take, and what resources they consume.

When this is useful:

Performance Analysis: When database queries are running slowly and you want to find out which queries are consuming the most resources (CPU, RAM, I/O).

Troubleshooting updates: To identify performance issues (“parameter sniffing” or poor execution plans) following software updates or database migrations and to force the use of old execution plans.

You can enable this using the following .bat script:

@ECHO OFF
:: ============================================================
:: enable-querystore-with-cleanup.bat -S <Server> [-E | -U <User> -P <Pass>]
:: ============================================================
SETLOCAL

SET SERVER=%~2
IF "%SERVER%"=="" (
    ECHO Usage: %~nx0 -S ^<Server^> [-E ^| -U ^<User^> -P ^<Pass^>]
    EXIT /B 1
)

SET AUTH=%3 %4 %5 %6 %7
IF "%AUTH: =%"=="" SET AUTH=-E

SET SQL=^
ALTER DATABASE VISTRAX_3_6 SET QUERY_STORE = ON;^
ALTER DATABASE VISTRAX_3_6 SET QUERY_STORE (OPERATION_MODE = READ_WRITE, MAX_STORAGE_SIZE_MB = 100, CLEANUP_POLICY = (STALE_QUERY_THRESHOLD_DAYS = 30));^
ALTER DATABASE VISTRAX_3_6_MANDATOR_1 SET QUERY_STORE = ON;^
ALTER DATABASE VISTRAX_3_6_MANDATOR_1 SET QUERY_STORE (OPERATION_MODE = READ_WRITE, MAX_STORAGE_SIZE_MB = 100, CLEANUP_POLICY = (STALE_QUERY_THRESHOLD_DAYS = 30));

sqlcmd -S "%SERVER%" %AUTH% -b -Q "%SQL%"

IF %ERRORLEVEL% EQU 0 (
    ECHO Query Store enabled successfully.
) ELSE (
    ECHO [ERROR] Failed to enable Query Store.
)

ENDLOCAL
EXIT /B %ERRORLEVEL%

First, you must run the following SQL query:

-------------------------------------------------------------------------------
-- This query checks index fragmentation in both databases
-- and defragments the indexes as needed.
-------------------------------------------------------------------------------
-- Fragmentation   Action          Reason
-- 10–30%          REORGANIZE      Online, no locking, lightweight
-- > 30%           REBUILD         Complete restructuring
-- < 10%           (skipped)       No action required
-------------------------------------------------------------------------------


-- ============================================
-- Defragment all indexes – VISTRAX_3_6
-- ============================================
USE VISTRAX_3_6;
GO

DECLARE @TableName    NVARCHAR(256);
DECLARE @IndexName    NVARCHAR(128);
DECLARE @Fragmentation DECIMAL(5,2);
DECLARE @SQL          NVARCHAR(512);

DECLARE frag_cursor CURSOR FOR
    SELECT
        OBJECT_SCHEMA_NAME(ips.object_id) + '.' + OBJECT_NAME(ips.object_id),
        i.name,
        ips.avg_fragmentation_in_percent
    FROM sys.dm_db_index_physical_stats(DB_ID(), NULL, NULL, NULL, 'LIMITED') ips
    JOIN sys.indexes i
        ON ips.object_id = i.object_id AND ips.index_id = i.index_id
    WHERE ips.index_id > 0          -- Exclude heaps
        AND ips.page_count >= 10    -- Only relevant indexes
        AND ips.avg_fragmentation_in_percent >= 10.0
    ORDER BY ips.avg_fragmentation_in_percent DESC;

OPEN frag_cursor;
FETCH NEXT FROM frag_cursor INTO @TableName, @IndexName, @Fragmentation;

WHILE @@FETCH_STATUS = 0
BEGIN
    IF @Fragmentation >= 30.0
    BEGIN
        SET @SQL = 'ALTER INDEX [' + @IndexName + '] ON ' + @TableName + ' REBUILD;';
        PRINT 'REBUILD  (' + CAST(@Fragmentation AS VARCHAR(5)) + '%)  -> ' + @TableName + '.' + @IndexName;
    END
    ELSE
    BEGIN
        SET @SQL = 'ALTER INDEX [' + @IndexName + '] ON ' + @TableName + ' REORGANIZE;';
        PRINT 'REORGANIZE  (' + CAST(@Fragmentation AS VARCHAR(5)) + '%) ->' + @TableName + '.' + @IndexName;
    END

    EXEC sp_executesql @SQL;

    FETCH NEXT FROM frag_cursor INTO @TableName, @IndexName, @Fragmentation;
END;

CLOSE frag_cursor;
DEALLOCATE frag_cursor;

PRINT 'VISTRAX_3_6 – Defragmentation completed.';
GO

-- ===================================================
-- Defragment all indexes – VISTRAX_3_6_MANDATOR_1
-- ===================================================
USE VISTRAX_3_6_MANDATOR_1;
GO

DECLARE @TableName    NVARCHAR(256);
DECLARE @IndexName    NVARCHAR(128);
DECLARE @Fragmentation DECIMAL(5,2);
DECLARE @SQL          NVARCHAR(512);

DECLARE frag_cursor CURSOR FOR
    SELECT
        OBJECT_SCHEMA_NAME(ips.object_id) + '.' + OBJECT_NAME(ips.object_id),
        i.name,
        ips.avg_fragmentation_in_percent
    FROM sys.dm_db_index_physical_stats(DB_ID(), NULL, NULL, NULL, 'LIMITED') ips
    JOIN sys.indexes i
        ON ips.object_id = i.object_id AND ips.index_id = i.index_id
    WHERE ips.index_id > 0
        AND ips.page_count >= 10
        AND ips.avg_fragmentation_in_percent >= 10.0
    ORDER BY ips.avg_fragmentation_in_percent DESC;

OPEN frag_cursor;
FETCH NEXT FROM frag_cursor INTO @TableName, @IndexName, @Fragmentation;

WHILE @@FETCH_STATUS = 0
BEGIN
    IF @Fragmentation >= 30.0
    BEGIN
        SET @SQL = 'ALTER INDEX [' + @IndexName + '] ON ' + @TableName + ' REBUILD;';
        PRINT 'REBUILD  (' + CAST(@Fragmentation AS VARCHAR(5)) + '%)  -> ' + @TableName + '.' + @IndexName;
    END
    ELSE
    BEGIN
        SET @SQL = 'ALTER INDEX [' + @IndexName + '] ON ' + @TableName + ' REORGANIZE;';
        PRINT 'REORGANIZE  (' + CAST(@Fragmentation AS VARCHAR(5)) + '%)  -> ' + @TableName + '.' + @IndexName;
    END

    EXEC sp_executesql @SQL;

    FETCH NEXT FROM frag_cursor INTO @TableName, @IndexName, @Fragmentation;
END;

CLOSE frag_cursor;
DEALLOCATE frag_cursor;

PRINT 'VISTRAX_3_6_MANDATOR_1 – Defragmentation completed.';
GO

You can then use the corresponding batch script to check the fragmentation of the batch script and defragment it if necessary:

@ECHO OFF
:: ============================================================
:: defrag-indices-on-necessity.bat -S <Server> [-E | -U <User> -P <Pass>]
:: ============================================================
SETLOCAL

SET SERVER=%~2
IF "%SERVER%"=="" (
    ECHO Usage: %~nx0 -S ^<Server^> [-E ^| -U ^<User^> -P ^<Pass^>]
    EXIT /B 1
)

SET AUTH=%3 %4 %5 %6 %7
IF "%AUTH: =%"=="" SET AUTH=-E

SET SQLFILE=%~dp0check-and-defrag-Indices-both-databases.sql

IF NOT EXIST "%SQLFILE%" (
    ECHO [ERROR] SQL file not found: %SQLFILE%
    EXIT /B 1
)

sqlcmd -S "%SERVER%" %AUTH% -b -i "%SQLFILE%"

IF %ERRORLEVEL% EQU 0 (
    ECHO Index defragmentation completed successfully.
) ELSE (
    ECHO [ERROR] Defragmentation failed.
)

ENDLOCAL
EXIT /B %ERRORLEVEL%