How to maintain the order of insertion in SQL Server

前端 未结 2 569
抹茶落季
抹茶落季 2020-12-11 13:31

I am just wondering if I can maintain the order of insertion of data in SQL Server?

I am working on my own project and it is kind of blog site having a number of pos

相关标签:
2条回答
  • 2020-12-11 13:36

    When you specify ORDER BY in an INSERT...SELECT statement, SQL Server will assign IDENTITY values in the order specified. However, that does not mean rows are necessarily inserted in that order.

    If you need rows returned in a specific order, you must use ORDER BY to guarantee ordering. Indexes can be leverage provide order data efficiently depending on the query particulars.

    0 讨论(0)
  • 2020-12-11 13:46

    You are misguided.

    SQL tables represent unordered sets. If you want a result set in a particular order, then you need to use an ORDER BY clause in the query. The SQL optimizer might not use the ORDER BY, finding another way to return the results in order.

    You can have an identity column that is not the primary key. But actually, you can have both an identity column and a guid column, with the former as the primary key and the latter as a unique key. Another solution is to have a CreatedAt datetime. You can use this for ordering . . . or even as a clustered index if you really wanted to.

    0 讨论(0)
提交回复
热议问题