SQL: Insert a List of Values into a Temp Table
In this article
- 1. CREATE TABLE #tmp Then INSERT ... VALUES With Multiple Rows
- 2. DECLARE @t TABLE for Table Variables
- 3. INSERT INTO ... SELECT With a VALUES Table Constructor
- 4. SELECT ... INTO #tmp When You Already Have a Query
- 5. STRING_SPLIT to Turn a Comma List Into Rows
- 6. PostgreSQL: VALUES, unnest, and string_to_array
- 7. MySQL: Multi-Row INSERT and Derived Tables
- 8. SQLite: No Temp Table Keywords Needed, but Mind the Limits
- 9. Batching Large Lists to Avoid Parameter and Statement Limits
- 10. Inserting the List Then Indexing and Joining It
- How to Choose
- Frequently Asked Questions
- Final Thoughts
The short answer: build the temp table first with CREATE TABLE #tmp (...) or a table variable, then insert all rows in one statement using INSERT INTO #tmp (cols) VALUES (v1), (v2), (v3); — and if the list is long or arrives as a comma-separated string, use a table constructor like VALUES (...), (...) in a SELECT derived table, or split the string with STRING_SPLIT in SQL Server, unnest(string_to_array(...)) in PostgreSQL, or a temporary table plus INSERT ... SELECT. This list covers the ten approaches that actually work across SQL Server, PostgreSQL, MySQL and SQLite, how they differ, and which one to reach for.
1. CREATE TABLE #tmp Then INSERT ... VALUES With Multiple Rows
The plainest method in SQL Server (and works the same on MySQL and PostgreSQL except for the name). You create the scratch table explicitly, then add every row in one multi-row VALUES clause. The advantage is that you control data types and column order up front, so a stray string in the third row fails loudly instead of silently coercing. Example: CREATE TABLE #Orders (OrderID int, Customer varchar(50), Total money); followed by INSERT INTO #Orders VALUES (1,'Ana',120.00),(2,'Ben',75.50);. Keep the list under roughly 1,000 rows per statement in older SQL Server versions — the row constructor limit is 1,000 — and split into batches beyond that.
2. DECLARE @t TABLE for Table Variables
SQL Server's table variable is a lighter alternative to a temp table: DECLARE @Orders TABLE (OrderID int, Customer varchar(50)); then insert into it the same way. Because its scope dies at the end of the batch, it is ideal inside stored procedures and functions where you do not want a named object lingering in tempdb. The trade-off is that the optimiser assumes the table variable holds one row, so joins against large tables can produce poor plans; for anything big, prefer #tmp.
3. INSERT INTO ... SELECT With a VALUES Table Constructor
Rather than a literal VALUES clause on INSERT, many dialects let you treat the list as a derived table: INSERT INTO #tmp (a,b) SELECT v.a, v.b FROM (VALUES (1,'x'),(2,'y')) AS v(a,b);. This is the cleanest way to combine a hard-coded list with logic — add a WHERE to the SELECT, join it to a real table, or compute a column. PostgreSQL and SQL Server both support the column aliases after the constructor; MySQL 8 requires an alias on the derived table too. It reads well when your list is a lookup set.
4. SELECT ... INTO #tmp When You Already Have a Query
If the values come from somewhere else rather than from literal typing, SELECT ... INTO #tmp FROM ... creates and fills the table in a single step and infers the column types from the source. It is shorter than CREATE TABLE plus INSERT and avoids type-mismatch mistakes. The catch: the temp table gets columns in source order with source types, and SELECT INTO does not copy indexes, constraints or keys, so add a CREATE INDEX afterwards if you will join on the scratch table repeatedly. Also note SELECT INTO fails if the target temp table already exists.
5. STRING_SPLIT to Turn a Comma List Into Rows
When the list arrives as text — 'red,green,blue' from a parameter — SQL Server 2016 and later has STRING_SPLIT: INSERT INTO #Colours (Name) SELECT value FROM STRING_SPLIT('red,green,blue', ',');. It produces a single column named value and a ordinal column in newer compatibility levels if you need to preserve order. It does not trim spaces, so 'red, green' yields ' green'; wrap the value in LTRIM(RTRIM(...)). In SQL Server 2012 or older, use a custom splitter or XML shredding instead.
6. PostgreSQL: VALUES, unnest, and string_to_array
PostgreSQL gives you the richest set of options. A bare VALUES list in a SELECT works as a relation: INSERT INTO tmp (a,b) VALUES (1,'x'),(2,'y');. For an array parameter, use unnest: INSERT INTO tmp (name) SELECT unnest(ARRAY['red','green']);. For text, INSERT INTO tmp (name) SELECT unnest(string_to_array('red,green', ',')); or the modern string_to_table('red,green', ','). All three are standard and efficient, and you can add WITH ORDINALITY to keep the original order when it matters.
7. MySQL: Multi-Row INSERT and Derived Tables
MySQL has supported the multi-row VALUES syntax for a long time: INSERT INTO tmp (a,b) VALUES (1,'x'),(2,'y');. If you need to split a delimited string, MySQL has no STRING_SPLIT, so join against a numbers table or use a recursive CTE: WITH RECURSIVE n AS (SELECT 1 AS i UNION ALL SELECT i+1 FROM n WHERE i < 10) SELECT SUBSTRING_INDEX(SUBSTRING_INDEX('a,b,c', ',', i), ',', -1) FROM n;. For temp tables, use a regular CREATE TEMPORARY TABLE, which is visible only to your connection and disappears when the session ends.
8. SQLite: No Temp Table Keywords Needed, but Mind the Limits
SQLite supports CREATE TEMP TABLE and the same multi-row VALUES clause, making the pattern portable. Two things to know: SQLite's default limit is 999 bound parameters per statement (recent builds raise it, but check your build), so very long literal lists should be split, and the VALUES constructor can also be used as a standalone query just like elsewhere. For a quick scratchpad, this is the whole syntax you need.
9. Batching Large Lists to Avoid Parameter and Statement Limits
Once you pass a few thousand rows, a single statement becomes fragile: SQL Server caps a row constructor at 1,000 rows, SQLite caps bound parameters, and drivers cap packet size. The fix is to loop in chunks — build a list of 500 rows, INSERT, clear, repeat — or use a bulk API such as SqlBulkCopy in .NET, COPY in PostgreSQL, or LOAD DATA in MySQL. Batching also keeps transaction log growth predictable and lets you commit in stages so a failure does not roll back everything.
10. Inserting the List Then Indexing and Joining It
Temp tables earn their keep when you reuse the list in several queries. After loading, add the indexes the join needs (CREATE INDEX IX_temp_Key ON #tmp (Key);) and join once rather than repeating IN (...) lists across statements. Statistics on temp tables are created automatically on first use in SQL Server, but on table variables they are not — another reason the #tmp route scales better for repeated lookups. Remember to DROP TABLE #tmp explicitly if the same session may reuse the name.
How to Choose
Start with the shape of your data. A short literal list inside one script points to a table variable or a single VALUES insert. A list that comes from another query points to SELECT ... INTO. A list that arrives as a delimited string needs a splitter — STRING_SPLIT on SQL Server, string_to_table or unnest on PostgreSQL, a CTE on MySQL. Size decides batching: below about a thousand rows a single statement is fine, above that loop in chunks or use a bulk loader. Reuse decides indexing: if you join the scratch data more than once, create the temp table explicitly, add an index, and drop it when done. Finally, check your dialect's row and parameter limits before you paste a 5,000-row literal and wonder why the statement fails.
Frequently Asked Questions
Can I insert multiple rows in one statement?
Yes. INSERT INTO #tmp (a,b) VALUES (1,'x'),(2,'y'),(3,'z'); works in SQL Server, PostgreSQL, MySQL and SQLite. Keep the SQL Server row count at or under 1,000 per statement.
What is the difference between a temp table and a table variable?
A temp table (#tmp) exists for the session and has statistics, so it optimises well for large data. A table variable (@t) is scoped to the batch and has no statistics, which suits small sets.
How do I split a comma-separated string into rows?
SQL Server 2016+ has STRING_SPLIT, PostgreSQL has string_to_table or unnest(string_to_array(...)), and MySQL needs a numbers table or recursive CTE. Trim the results — splitters keep leading spaces.
Why did my temp table disappear?
A #tmp table lives only for the connection that created it, and a table variable only for the batch. If your client opens a new connection per query, the table is gone; create and use it in the same session.
Can two sessions see the same temp table?
No. Local temp tables are private to the connection. If you truly need sharing, use a global temp table (##tmp in SQL Server), which is visible to all sessions and dropped when the last one releases it.
Final Thoughts
Pick the simplest form that fits the list you have: a multi-row VALUES insert for small literal data, a splitter for text, batching or bulk copy for large sets. Create the temp table explicitly whenever you need types, indexes or reuse, and drop it when you are finished so the next run starts clean.