Sql-server – Make sure two columns are sorted in the same order

sql servert-sql

I have a table like this:

CREATE TABLE T (
 ID INT NOT NULL IDENTITY PRIMARY KEY,
 CreateDateTime datetime2 NOT NULL,
 --other columns
)

How can I make sure that ID and CreateDateTime are both sorted in the same order? In other words, the following queries would return an identical order:

select * from T order by ID
select * from T order by CreateDateTime

I need this guarantee because for performance reasons I want to query a date range by filtering on the ID column. This is possible if the guarantee holds.

I want to fail DML that would violate that property. My intention is to catch bugs breaking this invariant.

Is there a way to do this without using triggers? My hope is that there is a more elegant solution.

Best Answer

I don't think it's easy to make such a guarantee and even if you do manage to make such an assertion actually work, it may slow down your Inserts into the table.

Since this is a performance issue for the ordering queries, here's a suggestion:

Make (CreateDateTime, ID) or (CreateDateTime) the clustered index of the table, instead of the (usual) clustered index on (ID) alone.

Then you can run queries with ORDER BY CreateDateTime and they will use the clustered index.