T-SQL 101: 137 Inserting rows with data from another SQL Server table

T-SQL 101: 137 Inserting rows with data from another SQL Server table

When you’re performing an INSERT, you can also get values from a query., rather than specifying the values in the INSERT statement.

In the example shown above, I’ve queried for a distinct list of order contacts and their phone number from the dbo.Orders table. I’m then inserting those values into the dbo.OrderContacts table.

These types of statements are easy to debug because I can just highlight the SELECT clause and run it to see what comes back.

I mentioned that the INSERT statement has an optional INTO word. I also mentioned that you should always include the list of inserted columns, even though that is also optional. Both of these apply here too.

Aliases

Even though it’s not strictly needed, I also like to apply aliases to all the columns being returned from the SELECT statement to make it clear which column in the INSERT they apply to.

I find that helps even more when the statements get complex, or where you are trying to debug the SELECT statement, to match up which values go to which inserted columns.

Learning T-SQL

It’s worth your while becoming proficient in SQL. If you’d like to learn a lot about T-SQL in a hurry, our Writing T-SQL Queries for SQL Server course is online, on-demand, and low cost.

2025-03-30