When multiple sessions request sequence values simultaneously, SQL Server allocates unique increasing numbers safely and efficiently. Values are assigned immediately without waiting for commit, so gaps may occur. Order between sessions isn’t guaranteed, but duplication never happens. CACHE improves performance but may increase gaps.
SQL Server SEQUENCE guarantees
that Every session gets a unique value No duplicates ever. Sequence values are
allocated atomically. Allocation is thread-safe
& highly concurrent SQL Server internally serializes sequence generation so
parallel sessions never clash. Sequence does NOT wait for
commit Values are assigned immediately. If a transaction rolls back then number
is not returned. Order is not guaranteed across sessions Even though
numbers are increasing, concurrency scheduling means that session 2 might
receive a number before Session 1 commits.
When we
enable CACHE then numbers are pre allocated and it will be Super-fast under
concurrency but if SQL crashes, cached numbers can be lost (gaps). When we are
not enabling CACHE its Strict persistence and slower than enable CACHE.
Let’s see the demo
Here creating a sequence
|
CREATE SEQUENCE Seq_Demo_HC AS BIGINT START WITH 1 INCREMENT BY 1 CACHE 50; |
Now we are using this Sequence in
multiple high transaction.
We have run this on several
window.
|
--window 1 BEGIN TRAN; SELECT NEXT VALUE FOR Seq_Demo_HC AS Seq_Demo_HC; -- Do NOT commit yet |
2nd window
3rd window
And so on.
All got unique IDs even before commit.
No comments:
Post a Comment
If you have any doubt, please let me know.