Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does the CACHE option of CREATE SEQUENCE work?

CREATE SEQUENCE has CACHE option

MSDN defines it as

[ CACHE [<constant> ] | NO CACHE ]

Increases performance for applications that use sequence objects by minimizing the number of disk IOs that are required to generate sequence numbers. Defaults to CACHE. For example, if a cache size of 50 is chosen, SQL Server does not keep 50 individual values cached. It only caches the current value and the number of values left in the cache. This means that the amount of memory required to store the cache is always two instances of the data type of the sequence object.

I understand it improves performance by avoiding reads from disk IO and maintaining some info in the memory that would help reliably generate the next number in the sequence, but I cannot imagine what a simple memory representation of the cache would look like for what the MSDN describes in the example.

Can someone explain how would the cache work with this sequence

CREATE SEQUENCE s
    AS INT
    START WITH 0  
    INCREMENT BY 25  
    CACHE 5

describing what the cache memory would hold when each of the following statements is executed independently:

SELECT NEXT VALUE FOR s -- returns 0
SELECT NEXT VALUE FOR s -- returns 25
SELECT NEXT VALUE FOR s -- returns 50
SELECT NEXT VALUE FOR s -- returns 75
SELECT NEXT VALUE FOR s -- returns 100
SELECT NEXT VALUE FOR s -- returns 125
like image 461
HappyTown Avatar asked Jul 08 '17 16:07

HappyTown


1 Answers

This paragraph in the doc is very helpful:

For an example, a new sequence is created with a starting value of 1 and a cache size of 15. When the first value is needed, values 1 through 15 are made available from memory. The last cached value (15) is written to the system tables on the disk. When all 15 numbers are used, the next request (for number 16) will cause the cache to be allocated again. The new last cached value (30) will be written to the system tables.

So, in your scenario

CREATE SEQUENCE s
    AS INT
    START WITH 0  
    INCREMENT BY 25  
    CACHE 5

You will have 0, 25, 50, 75 and 100 in Memory and you will get only one I/O write in disk: 100.

The problem you could have, explained in the the doc, is if the server goes down and you haven't used all the 5 items, next time you ask for a value you'll get 125.

like image 150
hardkoded Avatar answered Oct 05 '22 19:10

hardkoded