Skip to content
Advertisement

Insert distinct values from one table into another table

So for each distinct value in a column of one table I want to insert that unique value into a row of another table.

list = select distinct(id) from table0

for distinct_id in list
 insert into table1 (id) values (distinct_id)
end

Any ideas as to how to go about this?

Advertisement

Answer

Whenever you think about doing something in a loop, step back, and think again. SQL is optimized to work with sets. You can do this using a set-based query without the need to loop:

INSERT dbo.table1(id) SELECT DISTINCT id FROM dbo.table0;

There are some edge cases where looping can make more sense, but as SQL Server matures and more functionality is added, those edge cases get narrower and narrower…

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement