Insert Values Into Temp Table SQL: A Complete Guide
In this article
To insert values into a temporary table in SQL, you first create the table using a CREATE TABLE #TableName (SQL Server) or CREATE TEMPORARY TABLE TableName (MySQL/PostgreSQL) statement, and then use the INSERT INTO command to add data. This process allows you to store intermediate result sets, isolate data for complex calculations, or improve performance by reducing the number of times you query a large permanent table. Temporary tables exist only for the duration of the database session or transaction, meaning they are automatically deleted when the connection is closed.
What You'll Need
- A SQL database environment (such as SQL Server, MySQL, PostgreSQL, or Oracle).
- A query editor or command-line interface (CLI) with the necessary permissions to create tables.
- An understanding of the data types (e.g., INT, VARCHAR, DATE) required for the columns you intend to populate.
- A source of data, which can be manual values, a result set from another table, or a variable.
Step-by-Step
-
Define the Temporary Table Structure
Before you can insert values, the database must know what the table looks like. You must define the columns and their data types. In SQL Server, temporary tables are prefixed with a hash symbol (#). In MySQL or PostgreSQL, you use theTEMPORARYkeyword.
Example (SQL Server):
CREATE TABLE #UserSession (
SessionID INT,
UserName VARCHAR(50),
LoginTime DATETIME
);
Example (MySQL):
CREATE TEMPORARY TABLE UserSession (
SessionID INT,
UserName VARCHAR(50),
LoginTime DATETIME
); -
Insert Manual Values Using INSERT INTO
If you have a small set of known values, use theINSERT INTOstatement followed by theVALUESkeyword. You should explicitly list the columns you are targeting to avoid errors if the table schema changes later.
Example:
INSERT INTO #UserSession (SessionID, UserName, LoginTime)
VALUES (1, 'Alice', '2026-12-01 10:00:00'),
(2, 'Bob', '2026-12-01 10:15:00'); -
Insert Data from an Existing Table (INSERT INTO ... SELECT)
The most common use case for temporary tables is capturing a subset of data from a larger table for processing. Instead of using theVALUESkeyword, you follow theINSERT INTOstatement with aSELECTquery.
Example:
INSERT INTO #UserSession (SessionID, UserName, LoginTime)
SELECT UserID, UserName, LastLogin
FROM PermanentUsers
WHERE LastLogin > '2026-01-01';
Ensure that the columns in yourSELECTstatement match the data types and order of the columns in the temporary table definition. -
Verify the Inserted Data
Once the insertion is complete, run a simpleSELECT *query against the temporary table to ensure the data was transferred correctly and that no truncation occurred (which often happens with VARCHAR columns if they are too short).
Example:
SELECT * FROM #UserSession; -
Perform Operations and Drop the Table
Use the temporary table for your joins, aggregations, or filtering. While most systems drop temporary tables automatically when the session ends, it is a best practice to drop them manually to free uptempdbresources immediately.
Example:
DROP TABLE #UserSession;
Common Mistakes
One of the most frequent errors is attempting to insert data into a temporary table that has not yet been created. Unlike the SELECT INTO statement (which creates the table on the fly), the INSERT INTO statement requires the table to exist beforehand. If you receive an "Invalid object name" error, check that your CREATE TABLE script executed successfully before the insert.
Another common mistake is a mismatch between the number of columns specified in the INSERT INTO clause and the number of columns provided in the VALUES or SELECT clause. If your table has five columns but you only provide four values without specifying the column names, the database will throw an error because it does not know which column to leave null.
Data type mismatch is also a significant hurdle. For example, attempting to insert a long string into a VARCHAR(10) column will result in a "string or binary data would be truncated" error in SQL Server or a similar warning/error in other dialects. Always verify the maximum length of your source data before defining the temporary table schema.
Finally, users often forget that temporary tables are session-scoped. If you create a temporary table in one query window in your management tool and then try to insert values into it from a different query window, the second window will not see the table. Each connection to the database has its own isolated temporary workspace.
Tips
For better performance, consider adding an index to your temporary table after you have inserted the data but before you use it in a join. While creating a table with an index is possible, inserting data into an indexed table is generally slower than inserting into a heap and then creating the index. This is especially true for datasets exceeding 10,000 rows.
If you are using SQL Server and need a table that is accessible across different sessions (but still temporary), use a global temporary table by prefixing the name with double hashes (##GlobalTable). Be cautious with this approach, as any user with sufficient permissions can see and modify the data in a global temp table.
When dealing with very large datasets, use the TRUNCATE TABLE command if you need to clear the temporary table and reuse it within the same session. TRUNCATE is faster and uses fewer transaction log resources than DELETE FROM because it does not log individual row deletions.
To simplify your code, you can use SELECT ... INTO to create and populate a temporary table in one single step. This bypasses the need for a separate CREATE TABLE statement. For example: SELECT UserID, UserName INTO #TempUsers FROM PermanentUsers WHERE Status = 'Active'. This automatically assigns data types based on the source table.
Troubleshooting
If your INSERT INTO statement fails, the first step is to check for Constraint Violations. If you defined a Primary Key or a Unique Constraint on your temporary table, ensure that the data you are inserting does not contain duplicate values. If it does, you will need to use a DISTINCT keyword in your SELECT statement or clean the source data.
If you encounter Permission Errors, verify that your database user has the authority to create tables in the temporary database (such as tempdb in SQL Server). While most default roles allow this, some highly restricted environments may disable temporary table creation to prevent disk space exhaustion.
When you see Timeout Errors during a large insert, it is often because the transaction log is filling up or the source table is being locked. Try inserting the data in smaller batches using a WHERE clause to limit the rows per insert, or use the NOLOCK hint (in SQL Server) if the source data does not need to be perfectly consistent at that exact microsecond.
If the table seems to "disappear" unexpectedly, check if your connection was reset. In many cloud-based database environments, idle connections are killed after a few minutes. Once the connection is lost, the temporary table is instantly dropped. To fix this, wrap your creation, insertion, and processing logic into a single stored procedure or a single script execution block.
Frequently Asked Questions
Can I use a temporary table in a View?
No, views are permanent database objects and cannot reference temporary tables because the temporary table only exists for a specific session. If you need a reusable virtual table, use a Common Table Expression (CTE) or a permanent table.
What is the difference between a temp table and a table variable?
A temp table (#table) is physically stored in the temporary database and supports indexes and statistics, making it better for large datasets. A table variable (@table) exists primarily in memory (though it can spill to disk) and is generally faster for very small amounts of data but lacks the ability to have non-clustered indexes created after declaration.
Do temporary tables slow down the database?
If used excessively or left open in long-running sessions, they can put pressure on the tempdb or temporary storage area. However, they often speed up overall performance by allowing you to break a massive, complex query into smaller, manageable steps.
Can I join a temporary table with a permanent table?
Yes, this is one of the primary uses of temporary tables. You can perform INNER JOIN, LEFT JOIN, and other join types between a temporary table and any other table you have permission to access.
How do I rename a temporary table?
Most SQL dialects do not support renaming temporary tables using a simple RENAME command. The best practice is to create a new temporary table with the desired name and insert the data from the old one, or simply name it correctly during the CREATE TABLE phase.