top of page

SQL Server Development

Public·1 member

Sunil Dhaul
Sunil Dhaul

How to order row inserts into a table

In SQL Server, if we try to insert rows using a SELECT ORDER BY statement then the inserted rows are not inserted in the same sequence as the rows returned by the SELECT ORDER BY statement. In other words there is no use of having an ORDER BY clause for the SELECT statement when inserting rows.


The solution is to make the column on which you want to order the inserts as the primary key in the target table. Then if you insert using a SELECT statement the inserted rows in the target table would be ordered. Below examples use table variables to illustrate the solution, but the same concepts apply equally well to temp tables or regular tables in SQL Server.


Example code that orders row inserts in ascending order of Product


DECLARE @table_source TABLE (ProductId INT ,Product VARCHAR(50));
INSERT INTO @table_source (ProductId, Product) VALUES (2, 'Blue Trousers'), (1,…

35 Views
Sunil Dhaul
Sunil Dhaul
03 de set.

You can view the full article that discusses this approach and also a second approach to order inserted rows at https://www.kandoodevq.com/post/order-row-inserts-into-a-table

    Members

    • Sunil Dhaul
      Sunil Dhaul
    bottom of page