Return rows in the exact order they were inserted

A select query with no order by does not retrieve the rows in any particular order. You have to have an order by to get an order.

SQL Server does not have any default method for retrieving by insert order. You can do it, if you have the information in the row. The best way is a primary key identity column:

TableId int identity(1, 1) not null primary key

Such a column is incremented as each row is inserted.

You can also have a CreatedAt column:

CreatedAt datetime default getdate()

However, this could have duplicates for simultaneous inserts.

The key point, though, is that a select with no order by clause returns an unordered set of rows.

Leave a Comment