Explain Codes LogoExplain Codes Logo

How to create a table from select query result in SQL Server 2008

sql
join
data-types
best-practices
Anton ShumikhinbyAnton Shumikhin·Dec 27, 2024
TLDR

When you need to create a new table from query results in SQL Server 2008, you can use the SELECT INTO statement:

SELECT * INTO NewTable FROM ExistingTable;

This syntax copies data and structure from ExistingTable into a newly created table called NewTable. Be sure NewTable doesn't already exist, or you'll get a party crasher error.

Common obstacles and how to overcome

When using SELECT INTO you might face a few roadblocks. Here's how you can bypass them:

  • Data type alignment: Ensure the data types in your SELECT statement are compatible, especially when fetching from multiple tables.
  • Calling by names: A SELECT * is the lazy way. But if you need control, mention columns explicitly (col1, col2 ...).
  • Temp tables: To create a temporary table, use a sharpie and mark it with a hash (#). So, your syntax becomes SELECT ... INTO #Temp FROM ....
  • Link branching: To incorporate data from linked servers, ensure correct server references in your FROM clause.

Say adios to the "Incorrect syntax near the keyword 'AS'" error with SELECT INTO structure.

Making SELECT INTO work for you

Become a SELECT INTO maestro with these additional tricks:

Combine tables

Combine tables like a chef blending ingredients. Use JOIN to mingle data.

-- We are making a data cocktail! 🍹 SELECT t1.col1, t2.col2 INTO NewMixTable FROM Table1 as t1 JOIN Table2 as t2 ON t1.id = t2.id;

Filtered data

No need to keep all leftovers! Set conditions to filter out unwanted data.

-- Dieting? Here's a healthy data portion 🥦 SELECT column1, column2 INTO NewLeanTable FROM ExistingTable WHERE condition;

Computed columns

Add some custom flavors to your dataset. Include calculated columns that don't exist in your source table.

--Extra cheese? Let's bake a total value in there! 🧀 SELECT Name, Price, (Price*Quantity) AS TotalValue INTO NewEnrichedTable FROM Sales;

SELECT INTO under the hood

Alter your SELECT INTO mechanics by exploring some advanced scenarios:

Specify columns

When detail matters! Choose the exact columns you need and give them your preferred names or types.

-- Column pick and mix 🏗️ SELECT col1 AS Alias1, col2, CAST(col3 AS DataType) INTO CustomStructure FROM Blueprint;

Indexes and constraints

Remember! The SELECT INTO command is like moving houses without your furniture. You'll have to recreate indexes, keys, and constraints afterwards.

Partitioning

We all love an organized closet. SQL Server is no different. Use partitioning to separate large tables into more manageable sections.