SQL datatype with a constraint: each next element is greater/less than the previous one

StackOverflow https://stackoverflow.com/questions/23546549

  •  18-07-2023
  •  | 
  •  

Question

Does any of database management systems have a data type (it could be integer or datetime) with a constraint: each next element must be greater/less than the previous one?

Possible use case - storing current timestamp (timestamp should be with fractions of a second to prevent duplicate entries). Such column ends up being presorted and search speed for it is greatly improved without an index.

Was it helpful?

Solution

Such column ends up being presorted and search speed for it is greatly improved without an index.

SQL database management systems don't support the notion of "presorting" without an index. That index might be explicit or implicit. An explicit index comes about through a CREATE INDEX statement. An implicit index usually comes about through a PRIMARY KEY or UNIQUE constraint. (The logical constraint is usually implemented using a physical index.)

There are two issues here: being unique, and being consecutive.

The value of current_timestamp isn't guaranteed to be unique, even in serialized transactions. A constraint (like a primary key constraint or a unique constraint) can guarantee that a table store's unique timestamps, but it can't guarantee that each transaction will acquire a unique timestamp.

Sequential integers--by various names--are guaranteed to be unique and sequential, even in databases with high concurrency. (If you build them that way; you can create a sequence in PostgreSQL that goes backward, for example.) But they're not guaranteed to be consecutive; a rollback will "burn" a number, and the dbms won't try to re-use it.

Finally, the order in which rows are stored doesn't necessarily have anything to do with the order in which they're fetched and presented to the client, even when using an index or a clustered key. The only way to get rows back in a predictable order is to use an ORDER BY clause, which will almost always benefit from an index.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top