简体   繁体   中英

SQL Server Unique Constraints Without Sort Order

In an SQL Server database, I created a Unique Constraint to ensure that one of it's tables contains only unique pairs of values.

The problem now is that the order of records I get is different. The records are sorted, but I want them to come in original order, just as they exist in the table, without any sorting.

I've checked everywhere, but couldn't find a way to create a unique constraint without sort order. Is this supported at all?

The records are sorted, but I want them to come in original order, just as they exist in the table, without any sorting.

Ah, the old sort issue - SQL for beginners.

TABLES have a sort order that is the order of the clustered index. Missing that the odder is undefined.

RESULTS have NO ORDER UNLESS DEFINED . SQL can change the order if it thinks it can process a query better. This is FUNDAMENTAL - you deal with data sets, and data sets per se are not ordered.

So, if you want an order, ASK FOR IT.

but couldn't find a way to create a unique constraint without sort order.

Why would you need an order for a unique constraint? A unique index should suffice, or? I would NOT make uniqueness a constraint but put - standard - a unique index on the fields. Especially as the index is good for - validating that they are unique and thus needed anyway.

IF you want to get your records in the "original" order - you should use any field which will mark this order, such as an identity sequence / primary key (probably the best option you can use), or a creation date or anything else.
The rows in ur table (physically, in the file) are actually sorted by a particular order only when you use a clustered index , however, even in that case, there are no guarantees whatsover that this or any order will be preserved when you selected rows from that table, without any order by clause.
Usually, with a clustered table, You'll get the results in the order of the clustered index, however this is not something you can rely on, and wherever order is important, you should provide ORDER BY in your query.

Using ROW_NUMBER you can get how your order is stored without using sort_order. I hope it help.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM