I am using an AUTOINCREMENT PRIMARY KEY in-luau of a timestamp for ordering purposes in a GROUP BY clause.
This is a minimal example to illustrate only:
CREATE TABLE Items(
ItemId BIGINT IDENTITY (1, 1) NOT NULL,
CategoryId BIGINT,
CONSTRAINT [PK_Items] PRIMARY KEY NONCLUSTERED ([ItemId] ASC)
);
INSERT INTO Items(CategoryId)
-- 1 2 3 4 5
VALUES (1), (1), (2), (2), (3);
SELECT
LatestItemForCategory = MAX(ItemId)
FROM Items
GROUP BY CategoryId;
This should print:
LatestItemForCategory
2
4
5
I think this should work as well as a timestamp, generally, but I'm worried maybe T-SQL can do something "smart" like try to reuse deleted record's IDs which would mess up this kind of query.
I assume BIGINT has enough values to last till the end of time even for the biggest databases without rolling over?
Can I count on the primary key only increasing or does it roll-over at some point?
In T-SQL, every time you put a new record into a table that uses an auto-incrementing key, this key gets a number that's one more than the previous one.
It doesn't recycle numbers from entries you've deleted, so each record gets its own, higher number.
Regarding your concern about BigInt ID: The number type used, BIGINT, has a really large range, so it's unlikely you'll ever use them all up.
Notice: Just keep in mind, there might be some missing numbers if you remove records or if there are errors. Generally, this system works well for keeping your entries organized.
However, if your auto-increment ID reaches the maximum number it can go, it can't increase anymore. This is a problem because it means you can't add any more new entries. When this happens, the database will give you an error message.
and about comments which are placed under your posts I should mention that:
Usually, in T-SQL, each new record you add to a table gets a higher number than the last one if you're using auto-increment.
Deleting stuff doesn't mess up this order – if you delete something, the next new thing still gets the next number in line. But, if you manually reset this number system (called re-seeding), then you might get numbers that don't follow the usual order.
So, under normal and regular use, the numbers keep going up, but if you change the settings yourself, they might not.
The column gap ex: