Snowflake SQL Tutorial 111 - A Sequence Is Not In Order, And The Catalog Says So

Snowflake SQL · Episode 111

In this post we are going to cover sequences in Snowflake.

A sequence is an object that hands out numbers. You ask it for one with NEXTVAL and it gives you a number nobody else is going to get. That is its job, and it is the usual way to fill a key column.

A sequence looks like it promises two things: the numbers are unique, and the numbers go up. It delivers the first one every time. We are going to spend most of this post on the second one, because SHOW SEQUENCES has a column that quietly admits it was never promised.

We will start with the simplest sequence there is and ask it for a number, and build it up step by step from there.

Every query below was run on a real Snowflake account, and every result you see is the output it gave back.

Episode 111 of the Snowflake SQL: Zero to Hero series on TechBrothersIT.

Let's create a sequence and ask it for a number

Nothing clever in the settings. It starts at one and goes up by one. We will also make a table to keep the numbers in, because we will want them later.

Sample data
-- Sample data for this post.
-- One sequence with the simplest possible settings, and a table to put its
-- numbers into.
USE DATABASE DEMO_DB;
USE SCHEMA PUBLIC;

CREATE OR REPLACE SEQUENCE TICKET_SEQ_T111
    START = 1
    INCREMENT = 1
    COMMENT = 'episode 111 probe - dropped at the end of this file';

CREATE OR REPLACE TABLE TICKETS_T111 (
    TICKET_NO  INT,
    SUBJECT    VARCHAR(30)
);

Now let's ask the sequence for a number.

Query
SELECT TICKET_SEQ_T111.NEXTVAL AS THE_NUMBER;
Result1 row · 1 column
THE_NUMBER
1

One, which is exactly what we asked for. NEXTVAL is written as if it were a column on the sequence, and you can put it anywhere a value goes.

Now let's ask it twice more

Same statement, run again.

Query
SELECT TICKET_SEQ_T111.NEXTVAL AS THE_NUMBER;
Result1 row · 1 column
THE_NUMBER
101

Not two. Let's run it one more time.

Query
SELECT TICKET_SEQ_T111.NEXTVAL AS THE_NUMBER;
Result1 row · 1 column
THE_NUMBER
201

So with an increment of one, three separate calls gave us 1, 101 and 201. The numbers are unique and they are going up, but they are nowhere near consecutive.

This is the first thing to get used to. The increment is the step inside a call. It is not a promise about what the next call will get.

Can we ask it what it just gave us?

In a lot of databases you can. It is called CURRVAL, and it is how you get the key you have just inserted. Let's try it.

Refused
SELECT TICKET_SEQ_T111.CURRVAL AS THE_LAST_NUMBER;
Query failed — Snowflake returned an error
000904 (42000): SQL compilation error: error line 1 at position 7
invalid identifier 'TICKET_SEQ_T111.CURRVAL'

invalid identifier. There is no CURRVAL in Snowflake. The only way to know which number you got is to have kept it when it was handed to you.

The catalog will tell us where the sequence stands, which is not the same question.

Query
SELECT SEQUENCE_NAME, NEXT_VALUE
FROM INFORMATION_SCHEMA.SEQUENCES
WHERE SEQUENCE_SCHEMA = 'PUBLIC' AND SEQUENCE_NAME = 'TICKET_SEQ_T111';
Result1 row · 2 columns
SEQUENCE_NAMENEXT_VALUE
TICKET_SEQ_T111301

NEXT_VALUE is what it intends to give out next, not what it gave you. If two sessions are using the same sequence, reading that column tells you nothing about your own row.

Let's read the whole row SHOW SEQUENCES gives us

SHOW SEQUENCES returns one row per sequence, and it is worth reading all the way to the end.

Query
SHOW SEQUENCES LIKE 'TICKET_SEQ_T111';
Result1 row · 10 columns · scroll →
namedatabase_nameschema_namenext_valueintervalcreated_onownercommentowner_role_typeordered
TICKET_SEQ_T111DEMO_DBPUBLIC30112026-09-28 18:26:48.348000-07:00ACCOUNTADMINepisode 111 probe - dropped at the end of this fileROLEN

next_value and interval are the two we expected. interval is the increment under another name.

Now look at the last column. ordered says N.

Hold on to that N. It is the whole episode, and we will come back to it once we have a few more sequences to compare it with.

Now let's take ten numbers in one single statement

Three statements gave us three numbers a long way apart. Let's see what happens when one statement asks ten times.

GENERATOR gives us ten rows, and each of those rows calls NEXTVAL.

Query
INSERT INTO TICKETS_T111 (TICKET_NO, SUBJECT)
SELECT TICKET_SEQ_T111.NEXTVAL, 'ticket ' || TO_VARCHAR(SEQ4())
FROM TABLE(GENERATOR(ROWCOUNT => 10));
Result1 row · 1 column
number of rows inserted
10

Now let's look at the numbers it actually put in.

Query
SELECT TICKET_NO, SUBJECT FROM TICKETS_T111 ORDER BY TICKET_NO;
Result10 rows · 2 columns
TICKET_NOSUBJECT
301ticket 0
302ticket 1
303ticket 2
304ticket 3
305ticket 4
306ticket 5
307ticket 6
308ticket 7
309ticket 8
310ticket 9

They run straight through with no gap anywhere. Let's count that properly rather than reading it off the screen.

Query
SELECT COUNT(*)                        AS ROWS_PRESENT,
       MIN(TICKET_NO)                  AS LOWEST,
       MAX(TICKET_NO)                  AS HIGHEST,
       MAX(TICKET_NO) - MIN(TICKET_NO) + 1 AS SPAN,
       MAX(TICKET_NO) - MIN(TICKET_NO) + 1 - COUNT(*) AS NUMBERS_MISSING
FROM TICKETS_T111;
Result1 row · 5 columns
ROWS_PRESENTLOWESTHIGHESTSPANNUMBERS_MISSING
10301310100

NUMBERS_MISSING is 0. The span between the lowest and highest number is exactly the number of rows, so not one value was skipped.

And here is the step between each pair of neighbours, worked out with LEAD.

Query
SELECT TICKET_NO,
       LEAD(TICKET_NO) OVER (ORDER BY TICKET_NO) AS THE_NEXT_ONE,
       LEAD(TICKET_NO) OVER (ORDER BY TICKET_NO) - TICKET_NO AS THE_STEP
FROM TICKETS_T111
ORDER BY TICKET_NO;
Result10 rows · 3 columns
TICKET_NOTHE_NEXT_ONETHE_STEP
3013021
3023031
3033041
3043051
3053061
3063071
3073081
3083091
3093101
310NULLNULL

Nine steps of 1, and then the last row. It has no next row to compare itself with, so both of its columns are a real NULL rather than a zero.

So the gaps are not inside a statement. They are between statements. Three calls in three statements landed a hundred apart. Ten calls in one statement had no gaps at all.

What happens if we roll a transaction back?

A sequence hands out numbers. A transaction can be undone. Let's find out which one wins.

First, where the sequence stands before we start.

Query
SELECT NEXT_VALUE AS NEXT_VALUE_BEFORE
FROM INFORMATION_SCHEMA.SEQUENCES
WHERE SEQUENCE_SCHEMA = 'PUBLIC' AND SEQUENCE_NAME = 'TICKET_SEQ_T111';
Result1 row · 1 column
NEXT_VALUE_BEFORE
401

Now let's open a transaction and take three numbers inside it.

Query
BEGIN;
Result1 row · 1 column
status
Statement executed successfully.
Query
INSERT INTO TICKETS_T111 (TICKET_NO, SUBJECT)
SELECT TICKET_SEQ_T111.NEXTVAL, 'doomed ' || TO_VARCHAR(SEQ4())
FROM TABLE(GENERATOR(ROWCOUNT => 3));
Result1 row · 1 column
number of rows inserted
3
Query
SELECT COUNT(*) AS ROWS_VISIBLE_IN_HERE FROM TICKETS_T111;
Result1 row · 1 column
ROWS_VISIBLE_IN_HERE
13

Inside the transaction the ten rows from before and the three new ones are all visible. Now let's throw them away.

Query
ROLLBACK;
Result1 row · 1 column
status
Statement executed successfully.
Query
SELECT COUNT(*) AS ROWS_PRESENT, MAX(TICKET_NO) AS HIGHEST_TICKET
FROM TICKETS_T111;
Result1 row · 2 columns
ROWS_PRESENTHIGHEST_TICKET
10310

Back to ten rows, and the highest ticket number is the one the single insert finished on. The three rows are gone.

So did the sequence take its numbers back?

Query
SELECT NEXT_VALUE AS NEXT_VALUE_AFTER
FROM INFORMATION_SCHEMA.SEQUENCES
WHERE SEQUENCE_SCHEMA = 'PUBLIC' AND SEQUENCE_NAME = 'TICKET_SEQ_T111';
Result1 row · 1 column
NEXT_VALUE_AFTER
401

No. It stands exactly where it stood after the three numbers were taken. A rolled back transaction leaves a permanent gap, which is the answer you would expect and the reason a sequence is no good for an invoice number.

And then it handed out five

The catalog has just told us where the sequence is. So the next number should be that one, or something above it. Let's ask.

Query
SELECT TICKET_SEQ_T111.NEXTVAL AS THE_NEXT_NUMBER;
Result1 row · 1 column
THE_NEXT_NUMBER
5

Five.

That is below the highest ticket number sitting in the table, and a long way below what the catalog had just reported.

I cannot explain that and I am not going to invent a reason for it. What I can do is show you the rest of the evidence and then show you the column that says it was never promised.

Query
SELECT MAX(TICKET_NO)                  AS HIGHEST_IN_THE_TABLE,
       (SELECT NEXT_VALUE FROM INFORMATION_SCHEMA.SEQUENCES
        WHERE SEQUENCE_SCHEMA = 'PUBLIC'
          AND SEQUENCE_NAME = 'TICKET_SEQ_T111') AS THE_SEQUENCE_IS_AT
FROM TICKETS_T111;
Result1 row · 2 columns
HIGHEST_IN_THE_TABLETHE_SEQUENCE_IS_AT
310401

This one is captured after the call that gave us five, and THE_SEQUENCE_IS_AT reads the same as it did before that call. Handing out a number did not move the value the catalog reports.

What this is and is not

Everything on this page is one account on one evening, captured as it came back. The point is not that your account will hand out a five. The point is that nothing in a sequence's contract stops it, and the next section shows you where Snowflake writes that down.

Now let's change the increment

The increment can be altered on a sequence that already exists. Let's make it a hundred and watch two calls.

Query
ALTER SEQUENCE TICKET_SEQ_T111 SET INCREMENT = 100;
Result1 row · 1 column
status
Statement executed successfully.
Query
SELECT TICKET_SEQ_T111.NEXTVAL AS FIRST_ONE;
Result1 row · 1 column
FIRST_ONE
401

That is where the catalog said it was. Now the second call.

Query
SELECT TICKET_SEQ_T111.NEXTVAL AS SECOND_ONE;
Result1 row · 1 column
SECOND_ONE
100401

From 401 to 100401. The increment we set is not the distance we got between two statements, in the same way that an increment of one did not give us a distance of one earlier.

Let's put it back before we go on.

Query
ALTER SEQUENCE TICKET_SEQ_T111 SET INCREMENT = 1;
Result1 row · 1 column
status
Statement executed successfully.

How do you put a sequence back to the start?

You declare it again. There is no reset statement that works here, so CREATE OR REPLACE with a START is the way.

Query
CREATE OR REPLACE SEQUENCE TICKET_SEQ_T111 START = 1 INCREMENT = 1;
Result1 row · 1 column
status
Sequence TICKET_SEQ_T111 successfully created.
Query
SELECT TICKET_SEQ_T111.NEXTVAL AS AFTER_THE_RESTART;
Result1 row · 1 column
AFTER_THE_RESTART
1

Back to one. Which is the part that should worry you, because the table may already be using the numbers it is about to hand out again. Let's check whether it is.

Query
SELECT TICKET_NO, SUBJECT FROM TICKETS_T111
WHERE TICKET_NO <= 3 ORDER BY TICKET_NO;
Result0 rows · 2 columns
TICKET_NOSUBJECT

Nothing. No row in the table has a ticket number that low, because our numbers started in the three hundreds. So on this run the restarted sequence did not collide with anything.

Let's insert one more row and take the sequence's word for the number.

Query
INSERT INTO TICKETS_T111 (TICKET_NO, SUBJECT)
SELECT TICKET_SEQ_T111.NEXTVAL, 'a duplicate ticket number';
Result1 row · 1 column
number of rows inserted
1

Now let's look for any ticket number used twice.

Query
SELECT TICKET_NO, COUNT(*) AS ROWS_WITH_THIS_NUMBER
FROM TICKETS_T111
GROUP BY TICKET_NO
HAVING COUNT(*) > 1
ORDER BY TICKET_NO;
Result0 rows · 2 columns
TICKET_NOROWS_WITH_THIS_NUMBER

Empty again. There is no duplicate. The one the restarted sequence handed to the SELECT above was already spent, so this insert got a different number, and that number was free.

Query
SELECT (SELECT COUNT(*) FROM TICKETS_T111)                        AS ROWS_IN_THE_TABLE,
       (SELECT COUNT(DISTINCT TICKET_NO) FROM TICKETS_T111)       AS DISTINCT_NUMBERS,
       (SELECT MAX(TICKET_NO) - MIN(TICKET_NO) + 1 FROM TICKETS_T111)
                                                                  AS SPAN_OF_NUMBERS,
       (SELECT NEXT_VALUE FROM INFORMATION_SCHEMA.SEQUENCES
        WHERE SEQUENCE_SCHEMA = 'PUBLIC'
          AND SEQUENCE_NAME = 'TICKET_SEQ_T111')                  AS SEQUENCE_NEXT_VALUE;
Result1 row · 4 columns
ROWS_IN_THE_TABLEDISTINCT_NUMBERSSPAN_OF_NUMBERSSEQUENCE_NEXT_VALUE
1111309101

Read the first two columns together. The rows in the table and the distinct numbers in it are the same figure, so every number is used exactly once. The span is enormous by comparison, which is the gaps.

That is the promise, stated honestly. Unique, yes, every time. Dense, no. And as we are about to see, in order only if you ask for it.

Let's ask the catalog about a sequence properly

Everything from here on runs in a second worksheet with fresh sequences, so that the numbers start from a known place. Here is the first of them.

Query
CREATE OR REPLACE SEQUENCE PLAIN_SEQ_T111B START = 1 INCREMENT = 1;
Result1 row · 1 column
status
Sequence PLAIN_SEQ_T111B successfully created.

Now let's read its settings out of INFORMATION_SCHEMA.SEQUENCES.

Refused
SELECT SEQUENCE_NAME, START_VALUE, INCREMENT, NEXT_VALUE
FROM INFORMATION_SCHEMA.SEQUENCES
WHERE SEQUENCE_SCHEMA = 'PUBLIC' AND SEQUENCE_NAME = 'PLAIN_SEQ_T111B';
Query failed — Snowflake returned an error
001003 (42000): SQL compilation error:
syntax error line 1 at position 35 unexpected 'INCREMENT'.

A syntax error on a column that genuinely exists. INCREMENT is a reserved word, so the catalog's column of that name has to be written in double quotes.

Query
SELECT SEQUENCE_NAME, START_VALUE, "INCREMENT", NEXT_VALUE
FROM INFORMATION_SCHEMA.SEQUENCES
WHERE SEQUENCE_SCHEMA = 'PUBLIC' AND SEQUENCE_NAME = 'PLAIN_SEQ_T111B';
Result1 row · 4 columns
SEQUENCE_NAMESTART_VALUEINCREMENTNEXT_VALUE
PLAIN_SEQ_T111B111

Same query, two characters different, and now it runs. This is the sort of thing that costs ten minutes if nobody has ever shown it to you.

And here is every column that view has, in case you want something it reports that we are not using.

Query
SELECT COLUMN_NAME, DATA_TYPE
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = 'INFORMATION_SCHEMA' AND TABLE_NAME = 'SEQUENCES'
ORDER BY ORDINAL_POSITION;
Result18 rows · 2 columns
COLUMN_NAMEDATA_TYPE
SEQUENCE_CATALOGTEXT
SEQUENCE_SCHEMATEXT
SEQUENCE_NAMETEXT
SEQUENCE_OWNERTEXT
DATA_TYPETEXT
NUMERIC_PRECISIONNUMBER
NUMERIC_PRECISION_RADIXNUMBER
NUMERIC_SCALENUMBER
START_VALUETEXT
MINIMUM_VALUETEXT
MAXIMUM_VALUETEXT
NEXT_VALUETEXT
INCREMENTTEXT
CYCLE_OPTIONTEXT
CREATEDTIMESTAMP_LTZ
LAST_ALTEREDTIMESTAMP_LTZ
ORDEREDTEXT
COMMENTTEXT

ORDERED is in that list, near the bottom, as a TEXT column. Let's go and find out what it is for.

Now the column that says N: ORDER and NOORDER

We have one sequence declared with no opinion about ordering. Let's make two more that differ from it by exactly one word.

Query
CREATE OR REPLACE SEQUENCE ORDERED_SEQ_T111B START = 1 INCREMENT = 1 ORDER;
Result1 row · 1 column
status
Sequence ORDERED_SEQ_T111B successfully created.
Query
CREATE OR REPLACE SEQUENCE NOORDER_SEQ_T111B START = 1 INCREMENT = 1 NOORDER;
Result1 row · 1 column
status
Sequence NOORDER_SEQ_T111B successfully created.

Three sequences, the same start, the same increment. Let's show all three.

Query
SHOW SEQUENCES LIKE '%_T111B';
Result3 rows · 10 columns · scroll →
namedatabase_nameschema_namenext_valueintervalcreated_onownercommentowner_role_typeordered
NOORDER_SEQ_T111BDEMO_DBPUBLIC112026-09-28 18:39:01.991000-07:00ACCOUNTADMINROLEN
ORDERED_SEQ_T111BDEMO_DBPUBLIC112026-09-28 18:39:01.876000-07:00ACCOUNTADMINROLEY
PLAIN_SEQ_T111BDEMO_DBPUBLIC112026-09-28 18:39:00.247000-07:00ACCOUNTADMINROLEN

And let's pull out the four columns that matter so the last one is easy to read.

Query
SELECT "name", "next_value", "interval", "ordered"
FROM TABLE(RESULT_SCAN(LAST_QUERY_ID()))
ORDER BY "name";
Result3 rows · 4 columns
namenext_valueintervalordered
NOORDER_SEQ_T111B11N
ORDERED_SEQ_T111B11Y
PLAIN_SEQ_T111B11N

The one declared ORDER says Y. The one declared NOORDER says N. And the plain one, which said neither, also says N.

So NOORDER is the default. Nobody types it, and everybody gets it.

Snowflake writes it into the stored definition either way.

Query
SELECT GET_DDL('SEQUENCE', 'ORDERED_SEQ_T111B') AS THE_STORED_DEFINITION;
Result1 row · 1 column
THE_STORED_DEFINITION
create or replace sequence ORDERED_SEQ_T111B start with 1 increment by 1 order;
Query
SELECT GET_DDL('SEQUENCE', 'NOORDER_SEQ_T111B') AS THE_STORED_DEFINITION;
Result1 row · 1 column
THE_STORED_DEFINITION
create or replace sequence NOORDER_SEQ_T111B start with 1 increment by 1 noorder;

Let's ask each one for five numbers and compare

One word of difference should show up somewhere. Let's give both sequences the same treatment: five calls each, in five separate statements, with every number written down next to the call that got it.

Query
CREATE OR REPLACE TABLE HANDED_OUT_T111B (
    WHICH_SEQUENCE VARCHAR(20),
    CALL_NO        INT,
    THE_NUMBER     INT
);
Result1 row · 1 column
status
Table HANDED_OUT_T111B successfully created.
The calls
-- Five separate statements against each sequence, with every
-- number written down next to the call that got it.
INSERT INTO HANDED_OUT_T111B (WHICH_SEQUENCE, CALL_NO, THE_NUMBER)
SELECT 'ORDER', 1, ORDERED_SEQ_T111B.NEXTVAL;
INSERT INTO HANDED_OUT_T111B (WHICH_SEQUENCE, CALL_NO, THE_NUMBER)
SELECT 'ORDER', 2, ORDERED_SEQ_T111B.NEXTVAL;
INSERT INTO HANDED_OUT_T111B (WHICH_SEQUENCE, CALL_NO, THE_NUMBER)
SELECT 'ORDER', 3, ORDERED_SEQ_T111B.NEXTVAL;
INSERT INTO HANDED_OUT_T111B (WHICH_SEQUENCE, CALL_NO, THE_NUMBER)
SELECT 'ORDER', 4, ORDERED_SEQ_T111B.NEXTVAL;
INSERT INTO HANDED_OUT_T111B (WHICH_SEQUENCE, CALL_NO, THE_NUMBER)
SELECT 'ORDER', 5, ORDERED_SEQ_T111B.NEXTVAL;

INSERT INTO HANDED_OUT_T111B (WHICH_SEQUENCE, CALL_NO, THE_NUMBER)
SELECT 'NOORDER', 1, NOORDER_SEQ_T111B.NEXTVAL;
INSERT INTO HANDED_OUT_T111B (WHICH_SEQUENCE, CALL_NO, THE_NUMBER)
SELECT 'NOORDER', 2, NOORDER_SEQ_T111B.NEXTVAL;
INSERT INTO HANDED_OUT_T111B (WHICH_SEQUENCE, CALL_NO, THE_NUMBER)
SELECT 'NOORDER', 3, NOORDER_SEQ_T111B.NEXTVAL;
INSERT INTO HANDED_OUT_T111B (WHICH_SEQUENCE, CALL_NO, THE_NUMBER)
SELECT 'NOORDER', 4, NOORDER_SEQ_T111B.NEXTVAL;
INSERT INTO HANDED_OUT_T111B (WHICH_SEQUENCE, CALL_NO, THE_NUMBER)
SELECT 'NOORDER', 5, NOORDER_SEQ_T111B.NEXTVAL;

Now one grid with both sides of it.

Query
SELECT CALL_NO,
       MAX(IFF(WHICH_SEQUENCE = 'ORDER',   THE_NUMBER, NULL)) AS FROM_ORDER,
       MAX(IFF(WHICH_SEQUENCE = 'NOORDER', THE_NUMBER, NULL)) AS FROM_NOORDER
FROM HANDED_OUT_T111B
GROUP BY CALL_NO
ORDER BY CALL_NO;
Result5 rows · 3 columns
CALL_NOFROM_ORDERFROM_NOORDER
111
22101
332
443
55102

The ORDER column counts the way a person would. The NOORDER column does not. Look at the third call: it came back below the second one.

Let's have the step calculated rather than squinting at it.

Query
SELECT WHICH_SEQUENCE,
       CALL_NO,
       THE_NUMBER,
       THE_NUMBER - LAG(THE_NUMBER) OVER (PARTITION BY WHICH_SEQUENCE
                                          ORDER BY CALL_NO) AS THE_STEP
FROM HANDED_OUT_T111B
ORDER BY WHICH_SEQUENCE, CALL_NO;
Result10 rows · 4 columns
WHICH_SEQUENCECALL_NOTHE_NUMBERTHE_STEP
NOORDER11NULL
NOORDER2101100
NOORDER32-99
NOORDER431
NOORDER510299
ORDER11NULL
ORDER221
ORDER331
ORDER441
ORDER551

The first row of each sequence has no previous call, so its step is a real NULL. After that, every step on the ORDER side is 1.

On the NOORDER side there is a negative step. The sequence went backwards. That is not a bug and it is not a race. It is the N in that column, happening.

And the summary.

Query
SELECT MAX(IFF(WHICH_SEQUENCE = 'ORDER',   THE_NUMBER, NULL))
         - MIN(IFF(WHICH_SEQUENCE = 'ORDER',   THE_NUMBER, NULL)) AS SPAN_WITH_ORDER,
       MAX(IFF(WHICH_SEQUENCE = 'NOORDER', THE_NUMBER, NULL))
         - MIN(IFF(WHICH_SEQUENCE = 'NOORDER', THE_NUMBER, NULL)) AS SPAN_WITH_NOORDER,
       COUNT(DISTINCT IFF(WHICH_SEQUENCE = 'ORDER', THE_NUMBER, NULL))
                                                                 AS DISTINCT_FROM_ORDER,
       COUNT(DISTINCT IFF(WHICH_SEQUENCE = 'NOORDER', THE_NUMBER, NULL))
                                                                 AS DISTINCT_FROM_NOORDER
FROM HANDED_OUT_T111B;
Result1 row · 4 columns
SPAN_WITH_ORDERSPAN_WITH_NOORDERDISTINCT_FROM_ORDERDISTINCT_FROM_NOORDER
410155

The span the ordered sequence covered is tiny. The span the unordered one covered is wide. But the last two columns are the same as each other, and the same as the number of calls we made. Uniqueness held both ways. Only the ordering went.

And ten in one statement, both ways?

We saw earlier that one statement taking ten numbers had no gaps. Let's check that it holds for both of these.

Query
INSERT INTO HANDED_OUT_T111B (WHICH_SEQUENCE, CALL_NO, THE_NUMBER)
SELECT 'ORDER-10', SEQ4(), ORDERED_SEQ_T111B.NEXTVAL
FROM TABLE(GENERATOR(ROWCOUNT => 10));
Result1 row · 1 column
number of rows inserted
10
Query
INSERT INTO HANDED_OUT_T111B (WHICH_SEQUENCE, CALL_NO, THE_NUMBER)
SELECT 'NOORDER-10', SEQ4(), NOORDER_SEQ_T111B.NEXTVAL
FROM TABLE(GENERATOR(ROWCOUNT => 10));
Result1 row · 1 column
number of rows inserted
10
Query
SELECT WHICH_SEQUENCE,
       COUNT(*)                            AS NUMBERS,
       MIN(THE_NUMBER)                     AS LOWEST,
       MAX(THE_NUMBER)                     AS HIGHEST,
       MAX(THE_NUMBER) - MIN(THE_NUMBER) + 1 - COUNT(*) AS NUMBERS_MISSING
FROM HANDED_OUT_T111B
WHERE WHICH_SEQUENCE IN ('ORDER-10', 'NOORDER-10')
GROUP BY WHICH_SEQUENCE
ORDER BY WHICH_SEQUENCE;
Result2 rows · 5 columns
WHICH_SEQUENCENUMBERSLOWESTHIGHESTNUMBERS_MISSING
NOORDER-10102012100
ORDER-10106150

NUMBERS_MISSING is 0 on both rows. Inside a single statement you get a consecutive block whether you declared ORDER or not. The two blocks start in very different places, which is the gaps between statements again.

One more thing worth seeing. We never asked the plain sequence for a number. Let's check what the catalog says about it now.

Query
SHOW SEQUENCES LIKE 'PLAIN_SEQ_T111B';
Result1 row · 10 columns · scroll →
namedatabase_nameschema_namenext_valueintervalcreated_onownercommentowner_role_typeordered
PLAIN_SEQ_T111BDEMO_DBPUBLIC112026-09-28 18:39:00.247000-07:00ACCOUNTADMINROLEN
Query
SELECT "name", "next_value", "interval", "ordered"
FROM TABLE(RESULT_SCAN(LAST_QUERY_ID()));
Result1 row · 4 columns
namenext_valueintervalordered
PLAIN_SEQ_T111B11N

next_value is still where it started. A sequence does not drift on its own. It only moves when something asks it for a number.

So what is a sequence actually for? A column default

This is the job it is good at. You put NEXTVAL in a column's DEFAULT and then stop thinking about it.

Query
CREATE OR REPLACE SEQUENCE ORDER_SEQ_T111 START = 500 INCREMENT = 1;
Result1 row · 1 column
status
Sequence ORDER_SEQ_T111 successfully created.
Query
CREATE OR REPLACE TABLE ORDERS_T111 (
    ORDER_ID INT DEFAULT ORDER_SEQ_T111.NEXTVAL,
    CUSTOMER VARCHAR(30)
);
Result1 row · 1 column
status
Table ORDERS_T111 successfully created.

Now let's insert rows that never mention the id column at all.

Query
INSERT INTO ORDERS_T111 (CUSTOMER) SELECT 'Ana'
UNION ALL SELECT 'Ben'
UNION ALL SELECT 'Cleo';
Result1 row · 1 column
number of rows inserted
3
Query
SELECT ORDER_ID, CUSTOMER FROM ORDERS_T111 ORDER BY ORDER_ID;
Result3 rows · 2 columns
ORDER_IDCUSTOMER
500Ana
501Ben
502Cleo

Filled in for us, starting where we told the sequence to start. And the catalog records what the default actually is.

Query
SELECT COLUMN_NAME, COLUMN_DEFAULT, IS_NULLABLE
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = 'PUBLIC' AND TABLE_NAME = 'ORDERS_T111'
ORDER BY ORDINAL_POSITION;
Result2 rows · 3 columns
COLUMN_NAMECOLUMN_DEFAULTIS_NULLABLE
ORDER_IDDEMO_DB.PUBLIC.ORDER_SEQ_T111.NEXTVALYES
CUSTOMERNULLYES

The default for the id column is the sequence, written out with its database and schema. The customer column has no default, and its COLUMN_DEFAULT is a real NULL.

But a default is not a constraint

We covered that in Episode 100. A default only applies when you say nothing. Let's say something.

Query
INSERT INTO ORDERS_T111 (ORDER_ID, CUSTOMER) SELECT 1, 'Dan';
Result1 row · 1 column
number of rows inserted
1
Query
SELECT ORDER_ID, CUSTOMER FROM ORDERS_T111 ORDER BY ORDER_ID;
Result4 rows · 2 columns
ORDER_IDCUSTOMER
1Dan
500Ana
501Ben
502Cleo

Accepted, and now the ids are not in order and not dense. Nothing stopped us, because nothing was ever asked to. If the id has to be unique, that is a constraint's job, not a sequence's.

Is AUTOINCREMENT a sequence in disguise?

There is a second way to fill a key column, and it does not mention a sequence at all.

Query
CREATE OR REPLACE TABLE AUTO_T111 (
    ID    INT AUTOINCREMENT START 1 INCREMENT 1,
    LABEL VARCHAR(20)
);
Result1 row · 1 column
status
Table AUTO_T111 successfully created.
Query
INSERT INTO AUTO_T111 (LABEL) SELECT 'one'
UNION ALL SELECT 'two'
UNION ALL SELECT 'three';
Result1 row · 1 column
number of rows inserted
3
Query
SELECT ID, LABEL FROM AUTO_T111 ORDER BY ID;
Result3 rows · 2 columns
IDLABEL
1one
2two
3three

Those are the numbers people expect from a key column, and they are what a sequence would not give us across separate statements. Let's see what Snowflake stored.

Query
SELECT GET_DDL('TABLE', 'AUTO_T111')   AS AUTOINCREMENT_TABLE_DDL;
Result1 row · 1 column
AUTOINCREMENT_TABLE_DDL
create or replace TABLE AUTO_T111 ( ID NUMBER(38,0) autoincrement start 1 increment 1 noorder, LABEL VARCHAR(20) );

Read the end of the column definition. The same noorder default we met earlier is written in there, on a column that never mentioned a sequence.

And the sequence-backed table for comparison.

Query
SELECT GET_DDL('TABLE', 'ORDERS_T111') AS SEQUENCE_DEFAULT_TABLE_DDL;
Result1 row · 1 column
SEQUENCE_DEFAULT_TABLE_DDL
create or replace TABLE ORDERS_T111 ( ORDER_ID NUMBER(38,0) DEFAULT DEMO_DB.PUBLIC.ORDER_SEQ_T111.NEXTVAL, CUSTOMER VARCHAR(30) );

So is there a hidden sequence behind the autoincrement column? Let's count the sequences in the schema.

Query
SELECT COUNT(*) AS SEQUENCES_IN_THIS_SCHEMA,
       ARRAY_AGG(SEQUENCE_NAME) WITHIN GROUP (ORDER BY SEQUENCE_NAME)
         AS THEIR_NAMES
FROM INFORMATION_SCHEMA.SEQUENCES
WHERE SEQUENCE_SCHEMA = 'PUBLIC';
Result1 row · 2 columns
SEQUENCES_IN_THIS_SCHEMATHEIR_NAMES
2[ "ORDER_SEQ_T111", "TICKET_SEQ_T111" ]

Both of the sequences it found are ones we created by hand, and they are named in the second column. The autoincrement column did not add one. So no, it is not a sequence in disguise, even though it was stored with the same ordering default.

One last thing: let's tidy up

Sequences are dropped like anything else, and dropping one that a column still defaults to is allowed, so do the tables first.

Cleanup
-- Put the schema back the way we found it.
DROP TABLE    IF EXISTS TICKETS_T111;
DROP TABLE    IF EXISTS ORDERS_T111;
DROP TABLE    IF EXISTS AUTO_T111;
DROP TABLE    IF EXISTS HANDED_OUT_T111B;
DROP SEQUENCE IF EXISTS TICKET_SEQ_T111;
DROP SEQUENCE IF EXISTS ORDER_SEQ_T111;
DROP SEQUENCE IF EXISTS PLAIN_SEQ_T111B;
DROP SEQUENCE IF EXISTS ORDERED_SEQ_T111B;
DROP SEQUENCE IF EXISTS NOORDER_SEQ_T111B;
Query
SELECT CURRENT_DATABASE()                 AS THE_DATABASE,
       CURRENT_SCHEMA()                   AS THE_SCHEMA,
       (SELECT COUNT(*) FROM INFORMATION_SCHEMA.TABLES
        WHERE RIGHT(TABLE_NAME, 5) = '_T111') AS PROBE_TABLES_LEFT,
       (SELECT COUNT(*) FROM INFORMATION_SCHEMA.SEQUENCES
        WHERE RIGHT(SEQUENCE_NAME, 5) = '_T111') AS PROBE_SEQUENCES_LEFT,
       (SELECT COUNT(*) FROM CUSTOMERS)   AS DEMO_DB_IS_READABLE;
Result1 row · 5 columns
THE_DATABASETHE_SCHEMAPROBE_TABLES_LEFTPROBE_SEQUENCES_LEFTDEMO_DB_IS_READABLE
DEMO_DBPUBLIC0010
Query
SELECT CURRENT_DATABASE()                 AS THE_DATABASE,
       CURRENT_SCHEMA()                   AS THE_SCHEMA,
       (SELECT COUNT(*) FROM INFORMATION_SCHEMA.TABLES
        WHERE RIGHT(TABLE_NAME, 6) = '_T111B')     AS PROBE_TABLES_LEFT,
       (SELECT COUNT(*) FROM INFORMATION_SCHEMA.SEQUENCES
        WHERE RIGHT(SEQUENCE_NAME, 6) = '_T111B')  AS PROBE_SEQUENCES_LEFT,
       (SELECT COUNT(*) FROM CUSTOMERS)            AS DEMO_DB_IS_READABLE;
Result1 row · 5 columns
THE_DATABASETHE_SCHEMAPROBE_TABLES_LEFTPROBE_SEQUENCES_LEFTDEMO_DB_IS_READABLE
DEMO_DBPUBLIC0010

Nothing left from either worksheet, and the demo database still reads. Back where we started.

Key points

  • A sequence hands out unique numbers. That held in every grid on this page.
  • It does not hand out consecutive numbers. Three calls to a sequence with an increment of one gave 1, 101 and 201.
  • Ten calls inside one statement were consecutive, with nothing missing. So the gaps are between statements, not inside one.
  • It does not promise increasing numbers either. After a rolled back transaction this sequence handed out 5, below what was already in the table.
  • SHOW SEQUENCES has an ordered column, and on a sequence that says nothing about ordering it reads N. NOORDER is the default.
  • Declare the sequence with ORDER and the column reads Y, and five separate calls then came back in order.
  • Without it, one of the steps between consecutive calls was negative. The sequence went backwards.
  • Uniqueness held either way. The distinct numbers matched the calls made, with ORDER and without it.
  • There is no CURRVAL. You cannot ask a sequence what it just gave you, so keep the number when you get it.
  • A rolled back transaction leaves a permanent gap. The sequence does not give the numbers back.
  • INCREMENT is a reserved word, so reading that column out of INFORMATION_SCHEMA.SEQUENCES needs double quotes.
  • To put a sequence back to the start you declare it again with CREATE OR REPLACE, and it will happily hand out numbers your table may already be using.
  • A sequence in a column DEFAULT is what it is for. A default is not a constraint, so a row that names the column writes straight past it.
  • AUTOINCREMENT is not a sequence in disguise. It added no sequence to the schema, although it was stored with the same noorder default.
  • Use a sequence for a key nobody reads. Never for an invoice number.
Next in this series

Episode 112 — SHOW, DESCRIBE and COMMENT. Why you cannot put a WHERE clause on a SHOW, and the one function that turns its output into a table you can filter, count and join.

Every query and every result grid on this page was captured from a live Snowflake account (version 10.34.101) running the demo scripts for this episode. Two scripts were run: the first builds the _T111 objects, the second the _T111B ones, and the text says where it changes over. The number 5 that came back after the rollback is quoted as captured and is not explained, because nothing on this page explains it. Two captures came back empty and the text says so rather than describing what they were expected to show. Nothing is timed and no performance claims are made anywhere in this series. Sequence behaviour follows the Snowflake CREATE SEQUENCE documentation.

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.