Tag: Temp DB

  • Temp Tables in SQL Server

    Temp Tables in SQL Server

    Temp tables in SQL Server can improve the efficiency and performance of complex queries by breaking them down into smaller pieces, storing intermediate results in memory, and eliminating unnecessary data.

    In SQL Server, temporary tables are tables that are created for a specific purpose and are only available for the duration of the connection that created them. They can be created using either the # symbol or the ## symbol, with each symbol having slightly different behaviours.

    Local Temp Tables
    Temp tables created using the “#” symbol are known as local temp tables. These tables are only available to the connection that created them, and they are automatically dropped when the connection is closed. Local temp tables are commonly used and useful when you need to store and manipulate intermediate results within a query or stored procedure.

    Global Temp Tables
    These tables are available to any connection, and they are not automatically dropped when the connection that created them is closed. Global temp tables are useful when you need to share data between different connections or when you want to store data that needs to persist beyond the lifetime of a single connection or session.

    Below I’ll demo how to perform the following on Temp Tables in SQL Server:
    Create a Local Temp Table
    Insert Rows into Temp Table
    Create an Index on Temp Table
    Select From Temp Table
    Drop Temp Table

    Create a Local Temp Table

    This statement creates a temporary table called #Chicken in a local scope:

    -- Create a local temp table called #Chicken
    CREATE TABLE #Chicken (
       ID INT,
       Name VARCHAR(50),
       Type VARCHAR(50),
       Price DECIMAL(18,2)
    );
    

    This temp table will be short-lived as it exists only for the duration of my current SSMS session. It is only accessible from the session in which it was created and is automatically dropped when the session ends (when I close the query window or it disconnects).

    Insert Rows into Temp Table

    This statement inserts four rows of data into the temporary table #Chicken:

    -- Insert four rows of data into the #Chicken table
    INSERT INTO #Chicken (ID, Name, Type, Price)
    VALUES (1, 'Roasted Chicken', 'Whole', 14.99),
           (2, 'Fried Chicken', 'Wings', 9.99),
           (3, 'Grilled Chicken', 'Breast', 12.99),
           (4, 'Teriyaki Chicken', 'Stir Fry', 11.99);
    

    Create an Index on Temp Table

    In this next statement, I’m creating an index on the #Chicken temporary table to improve query performance:

    -- Create an index on the Type column to improve query performance
    CREATE INDEX idx_chicken_type ON #Chicken (Type);
    

    An index in MSSQL is a data structure that allows faster search and retrieval of data from a table. By creating an index on the Type column of the #Chicken table, the database engine can more efficiently locate and retrieve rows based on the values in that column.

    Select From Temp Table

    This statement retrieves all rows from the temporary table #Chicken:

    -- Retrieve all rows from the #Chicken table
    SELECT * FROM #Chicken;
    
    Create Temp Table SQL Server

    Drop Temp Table

    This statement drops a temporary table called #Chicken.

    -- Drop local temp table (also happens on session disconnect)
    DROP TABLE #Chicken;
    

    When a temporary table is no longer needed, it can be removed using the DROP TABLE statement. Dropping a temporary table removes it from the database and frees up the space it occupied.

    We should give global temp tables more attention for this clean-up part. Global temp tables are visible to all connections which means they are not automatically dropped. It is important to drop global temp tables when they are no longer needed to prevent clutter and ensure efficient use of resources.

  • Move Temp DB SQL Server

    Move Temp DB SQL Server

    A common best practice for SQL Server DBA’s is to have Temp DB files stored on a separate drive, especially ensuring that it’s not on the C:\ drive and sharing with the OS.

    This is because Temp DB can grow very large, very quickly. The growth of Temp DB Files depends on the workload/queries happening on your SQL Server. Temp DB growth can happen on both the data and log files.

    This post is a tutorial on how to move all Temp DB files from one volume to another in SQL Server.

    Downtime is required for this action, so we should ensure we have a planned maintenance window for this work.

    Move Temp DB Files MSSQL

    First, I’m going to use sp_helpfile to view logical Temp DB names.

    -- move temp db files sql server
    USE temp db;
    GO
    
    -- check physical names and attributes for current database
    exec sp_helpfile;
    
    sp_helpfile sql

    We can see this SQL Server Instance has 8x temp_db data files and one temp_db log file.

    Next, run the following script to generate the ALTER statements required to move these files. You’ll need to amend the FILENAME parameter to the new location.

    Temp DB SQL Server

    Grab the SQL output from here and then run the ALTER DATABASE commands.

    -- move temp_DB database to new location on disk
    -- (amend temp_db to actual db name)
    ALTER DATABASE temp_db MODIFY FILE (NAME = [tempdev], FILENAME = 'D:\mssql_temp_db\tempdev.mdf');
    ALTER DATABASE temp_db MODIFY FILE (NAME = [templog], FILENAME = 'D:\mssql_temp_db\templog.ldf');
    ALTER DATABASE temp_db MODIFY FILE (NAME = [temp2], FILENAME = 'D:\mssql_temp_db\temp2.mdf');
    ALTER DATABASE temp_db MODIFY FILE (NAME = [temp3], FILENAME = 'D:\mssql_temp_db\temp3.mdf');
    ALTER DATABASE temp_db MODIFY FILE (NAME = [temp4], FILENAME = 'D:\mssql_temp_db\temp4.mdf');
    ALTER DATABASE temp_db MODIFY FILE (NAME = [temp5], FILENAME = 'D:\mssql_temp_db\temp5.mdf');
    ALTER DATABASE temp_db MODIFY FILE (NAME = [temp6], FILENAME = 'D:\mssql_temp_db\temp6.mdf');
    ALTER DATABASE temp_db MODIFY FILE (NAME = [temp7], FILENAME = 'D:\mssql_temp_db\temp7.mdf');
    ALTER DATABASE temp_db MODIFY FILE (NAME = [temp8], FILENAME = 'D:\mssql_temp_db\temp8.mdf');
    
    alter database sql server

    The file “tempdev” has been modified in the system catalog. The new path will be used the next time the database is started.

    The above output message informs that we have to restart the SQL Service for this change to take effect. So let’s do that now.

    Restart MS SQL Service

    Once done, we can check the active temp db files in our new directory.

    Temp Database SQL Files

    And verify in MSSQL by using exec sp_helpfile as above in this demo, or by opening the database Shrink File window in SSMS.

    MSSQL Temp Database Files

    Lastly, remember to delete the old Temp DB files from where you moved them from.

    I hope this guide provided you with some insight and that your change goes without issues! Feel free to check out my Database Admin tips tag for more random posts from a SQL DBA.