Category: physical design

  • Find and Change (N)VARCHAR(MAX) to (N)VARCHAR(XXX)

    I know, I know, everything I do is rushed and not properly explained, apologies for that. Anyway.
    During some investigation, I came across some badly designed tables where most of the columns meant to hold character data were NVARCHAR(MAX), all this while the maximum length of the strings were something in the area of 30-50 characters. It has been widely documented why this is a bad idea in terms of performance, so I will only put a script in here that will attempt to categorize them from 1 to 255, 255 to 512, 512 to 1024, etc.

    SET NOCOUNT ON;
    IF OBJECT_ID('tempdb..#MaxVarChar') IS NOT NULL
    DROP TABLE #MaxVarChar;
    CREATE TABLE #MaxVarChar
    (
    SchemaName NVARCHAR(128) COLLATE DATABASE_DEFAULT,
    TableName NVARCHAR(128) COLLATE DATABASE_DEFAULT,
    ColumnName NVARCHAR(128) COLLATE DATABASE_DEFAULT,
    TypeName SYSNAME COLLATE DATABASE_DEFAULT,
    MaxLen INT NOT NULL
    );
    DECLARE @sql NVARCHAR(MAX) = N'';
    ;WITH VarMaxCols AS
    (
    SELECT
    s.name AS SchemaName,
    t.name AS TableName,
    c.name AS ColumnName,
    ty.name AS TypeName
    FROM sys.columns c
    JOIN sys.types ty
    ON c.user_type_id = ty.user_type_id
    JOIN sys.tables t
    ON c.object_id = t.object_id
    JOIN sys.schemas s
    ON t.schema_id = s.schema_id
    WHERE ty.name IN (N'varchar', N'nvarchar')
    AND c.max_length = -1
    AND t.is_ms_shipped = 0
    )
    SELECT
    @sql = @sql + N'
    INSERT INTO #MaxVarChar
    (
    SchemaName,
    TableName,
    ColumnName,
    TypeName,
    MaxLen
    )
    SELECT
    ' + QUOTENAME(SchemaName, '''') + N',
    ' + QUOTENAME(TableName, '''') + N',
    ' + QUOTENAME(ColumnName, '''') + N',
    ' + QUOTENAME(TypeName, '''') + N',
    ISNULL(
    MAX(
    ISNULL(' +
    CASE
    WHEN TypeName = N'nvarchar' THEN
    N'DATALENGTH(' + QUOTENAME(ColumnName) + N') / 2'
    ELSE
    N'DATALENGTH(' + QUOTENAME(ColumnName) + N')'
    END
    + N', 0)
    ),
    0
    )
    FROM ' + QUOTENAME(SchemaName) + N'.' + QUOTENAME(TableName) + N';'
    FROM VarMaxCols
    ORDER BY
    SchemaName,
    TableName,
    ColumnName;
    IF LEN(@sql) > 0
    EXEC sys.sp_executesql @sql;
    ;WITH VarMaxCols AS
    (
    SELECT
    s.name AS SchemaName,
    t.name AS TableName,
    c.name AS ColumnName,
    ty.name AS TypeName,
    c.is_nullable,
    c.collation_name
    FROM sys.columns c
    JOIN sys.types ty
    ON c.user_type_id = ty.user_type_id
    JOIN sys.tables t
    ON c.object_id = t.object_id
    JOIN sys.schemas s
    ON t.schema_id = s.schema_id
    WHERE ty.name IN (N'varchar', N'nvarchar')
    AND c.max_length = -1
    AND t.is_ms_shipped = 0
    )
    SELECT
    N'ALTER TABLE '
    + QUOTENAME(vc.SchemaName)
    + N'.'
    + QUOTENAME(vc.TableName)
    + N' ALTER COLUMN '
    + QUOTENAME(vc.ColumnName)
    + N' '
    + UPPER(vc.TypeName)
    + N'('
    + CASE
    WHEN vc.TypeName = N'nvarchar' THEN
    CASE
    WHEN m.MaxLen <= 255 THEN N'255'
    WHEN m.MaxLen <= 512 THEN N'512'
    WHEN m.MaxLen <= 1024 THEN N'1024'
    WHEN m.MaxLen <= 2048 THEN N'2048'
    ELSE N'4000'
    END
    WHEN vc.TypeName = N'varchar' THEN
    CASE
    WHEN m.MaxLen <= 255 THEN N'255'
    WHEN m.MaxLen <= 512 THEN N'512'
    WHEN m.MaxLen <= 1024 THEN N'1024'
    WHEN m.MaxLen <= 2048 THEN N'2048'
    WHEN m.MaxLen <= 4000 THEN N'4000'
    ELSE N'8000'
    END
    END
    + N')'
    + CASE
    WHEN vc.collation_name IS NOT NULL THEN
    N' COLLATE ' + vc.collation_name
    ELSE
    N''
    END
    + N' '
    + CASE
    WHEN vc.is_nullable = 1 THEN N'NULL'
    ELSE N'NOT NULL'
    END
    + N';' AS AlterStatement,
    m.MaxLen
    FROM VarMaxCols vc
    JOIN #MaxVarChar m
    ON m.SchemaName = vc.SchemaName COLLATE DATABASE_DEFAULT
    AND m.TableName = vc.TableName COLLATE DATABASE_DEFAULT
    AND m.ColumnName = vc.ColumnName COLLATE DATABASE_DEFAULT
    AND m.TypeName = vc.TypeName COLLATE DATABASE_DEFAULT
    WHERE
    (
    vc.TypeName = N'nvarchar'
    AND m.MaxLen <= 4000
    )
    OR
    (
    vc.TypeName = N'varchar'
    AND m.MaxLen <= 8000
    )
    ORDER BY
    vc.SchemaName,
    vc.TableName,
    vc.ColumnName;

    It basically checks the base tables for columns that have VARCHAR(MAX) or NVARCHAR(MAX) as definition and then it checks for the maximum length of the strings you have stored. Just make sure you set Results To Text (CTRL + T) and not grid and you should have the scripts generated for you.
    Of course, you must remember that the ALTER TABLE ... ALTER COLUMN will fail if the column is part of an index, constraint, etc.
    You also must take into account that if you have a ton of columns that qualify, a ton of ALTER statements will be generated, which is not ideal, to put it mildly.

    One caveat here: my original script transformed all the columns into NVARCHAR(XXX) so I could align them with the rest of the project. I ran it through ChatGPT and it modified it to leave the columns in their original data type (VARCHAR or NVARCHAR). So make sure you test it before even thinking to use it on prod databases.
    Just remember some of your columns might have data that already goes beyond the limits you want to set, so they will not be found in the final set of ALTER statements.
    DO NOT DO ANY CHANGES UNTIL YOU TALK TO YOUR DEV TEAM!

  • Why is important to separate data from indexes

    Hello again.

    You all probably heard here and there that separating data from the indexes is good. Some of you even went down that road and actually did it. Which is good.

    There are also a ton of articles on this topic and the ones that come quickly to my mind are the ones authored by Paul Randal (here, here and here). These are not the only ones, most likely.

    I will try not to repeat what others already said as to why. I will, however, try to show you why.

    Here’s the setup. There’ll be 2 tests. One for a one-filegroup database (PRIMARY) and one with a 3-filegroup database (PRIMARY, DATA and INDEX). To enhance a bit the results I’ve placed the databases on 2 USB sticks. The TLOG was placed on the local drive, to avoid skewing the results with the I/O related to that.

    The test itself will have the following steps:

    • create the db and the tables
    • populate the tables
    • start PerfMon
    • run random scripts (well, pseudo-random :), you’ll see )
    • cleanup

    While doing the above, I’ll use a simple PerfMon session to capture the disks response times.

    So let’s get started. We’ll create 3 tables, same schema for all 3. We’ll populate each table and then run some scripts against them. You can download the scripts here. You might want to adjust the paths, the sizes of the files. In the scripts that populates the tables, you can change the number of the records inserted by changing the number of the batches (GO 5000).

    To run the scripts, I’ve used the SQLQueryStress (oldie, but goldie – available here). The stored procedure I’ve used, generates a list of scripts from a given folder (see the code) and based on a randomly generated number, executes one of the scripts. Depending on the number of scripts, you might want to adjust the module operand (in my case, 12 as I have 12 scripts). Please also note that the stored procedure called by the SQLQueryStress is using xp_cmdshell. Make sure this is enabled before running it. Or, if this is an issue, feel free to change the code to use Powershell, for example. Alternatively, you can adjust the whole process to be a dynamic code stored in temp table of some sort (copy and paste the workload scripts in an VARCHAR(MAX) column).

    And now let’s see the results. Before anything else, briefly, the setup:

    • One FG: TLOG located on local drive and PRIMARY FG located on F: (USB stick)
    • MultiFG: TLOG and PRIMARY FG located on local drive, DATA located on F (USB stick) and INDEX on H (also an USB stick)

    Here’s a summary of the PerfMon data (file can be downloaded here).

    PerfMon_Summary

    Looking at the figures above, it is clear that having multiple FGs definitely helps. The average response times (Avg Disk Sec / Read and Avg Disk Sec / Write) improves considerably. The read response time improved with more than 100%, the write response time improved with more than 200% on the F drive. As there’s no data in the one filegroup case for H drive, there’s no data to compare against. The max response times also improves, as it can be seen in the highlighted cells.

    All the PerfMon graphs can be seen here, as a gallery:

    Considering that my setup was a rather simple one, in a real life scenario where things can get complicated really ugly, this approach can help improving the performance big time. Of course, as always, it is a matter of “it depends”, but as a rule of thumb, if the table is going to be hammered pretty heavy, maybe it makes sense to split the data from the indexes. Maybe having its own filegroup will help even more (here some other factors will need to be taken into account like table size, usage pattern, expected fragmentation, etc). Placing these on a LUN or on a storage that’s not so hammered may further help balancing out the I/O. I will not go any further into this, as there are a lot of other articles on the matter (see the 3 links from the beginning of this post, for example).

    So next time you have to design the physical design of a database, think twice before just running the CREATE DATABASE statement or just blindly using the default options. This approach can also be used when troubleshooting performance issues. One thing that should always be checked is the underlying physical design of the affected tables.

    What could be done differently to test this more thoroughly ? Well, one could use a server-side trace (SST) as well and correlate the 2 traces (PerfMon and SST) in SQL Profiler. This way you can also see the impact of each test script in terms of response times. Extended events can also be used to track the activity, but cannot be correlated in Profiler that nicely as an SST (or at least I am not aware of such a feature).

    In addition to all of the above, sys.dm_io_virtual_stats can also be queried and see the impact from inside SQL Server on the affected files. Just make sure to query it in a loop, as the result set is cumulative.

    Another thing that can be done differently (and this is something that you can try out), is to try and simulate workloads separately. First only reads, then only writes and then combined. This will allow you to see the improvement for each of the I/O pattern.

    Another interesting thing to watch is the change in the I/O graphs when the tables are populated. But I’ll let you discover that for yourselves.

    Enjoy.