Snowflake SQL Tutorial 106 - UNDROP Is Not A Stack, And TRUNCATE Does Not Reset AUTOINCREMENT

Snowflake SQL · Episode 106

In this post we are going to cover DROP, UNDROP and TRUNCATE in Snowflake, and DELETE alongside them for comparison.

All four of them remove something. DELETE removes rows you name. TRUNCATE removes every row and keeps the table. DROP removes the table itself. UNDROP asks for a dropped table back.

We will start with one table that has things worth losing, and take them away one way at a time. Two of the answers along the way are not the ones I expected.

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

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

Let's create a table with something to lose

A table with only an ID in it would not tell us very much. So this one has four columns and each of them is a different thing to lose: an AUTOINCREMENT id, a NOT NULL label, a column with a default, and a timestamp with a default. The table itself carries a COMMENT as well.

Copy this into a worksheet and run it once.

Sample data
-- Sample data for this post.
-- One table, built so that there are several different things to lose.
USE DATABASE DEMO_DB;
USE SCHEMA PUBLIC;

CREATE OR REPLACE TABLE REMOVE_T106 (
    ID     INT           AUTOINCREMENT START 1 INCREMENT 1,
    LABEL  VARCHAR(30)   NOT NULL,
    GRADE  VARCHAR(10)   DEFAULT 'standard',
    ADDED  TIMESTAMP_NTZ DEFAULT CURRENT_TIMESTAMP()
)
COMMENT = 'episode 106 probe - dropped at the end of this file';

INSERT INTO REMOVE_T106 (LABEL)
SELECT 'alpha'
UNION ALL SELECT 'beta'
UNION ALL SELECT 'gamma'
UNION ALL SELECT 'delta';

Now let's look at what we just created.

Query
SELECT ID, LABEL, GRADE FROM REMOVE_T106 ORDER BY ID;
Result4 rows · 3 columns
IDLABELGRADE
1alphastandard
2betastandard
3gammastandard
4deltastandard

Four rows. The ids are one to four, and we never typed one of them — the AUTOINCREMENT handed them out. The grade says standard on every row, which is the default doing its job.

Now let's ask the catalog what it knows about the table.

Query
SELECT TABLE_NAME, ROW_COUNT, COMMENT
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = 'PUBLIC' AND TABLE_NAME = 'REMOVE_T106';
Result1 row · 3 columns
TABLE_NAMEROW_COUNTCOMMENT
REMOVE_T1064episode 106 probe - dropped at the end of this file

The row count agrees with the grid above, and the comment came back word for word. Both of those are worth noting now, because we are going to check them again after each kind of removal.

Let's start with DELETE, which takes rows

DELETE is the gentlest of the four. We tell it which rows to remove and it removes those.

Query
DELETE FROM REMOVE_T106 WHERE LABEL = 'beta';
Result1 row · 1 column
number of rows deleted
1

One row deleted. Let's see what is left.

Query
SELECT ID, LABEL FROM REMOVE_T106 ORDER BY ID;
Result3 rows · 2 columns
IDLABEL
1alpha
3gamma
4delta

beta is gone and there is a gap in the ids where it was. The table is still here, the other rows are untouched, and nothing about the table's shape has changed.

That is the whole of DELETE. It is ordinary DML, it takes rows and nothing else, and we covered it properly back in Level 10.

Now let's insert one more row and look at the id it gets

This is where the episode takes its first turn, and it is nothing to do with removing things.

We deleted a row, so there is a gap. Let's insert one more row without naming the id, which means the AUTOINCREMENT picks it.

Query
INSERT INTO REMOVE_T106 (LABEL) SELECT 'epsilon';
Result1 row · 1 column
number of rows inserted
1

The declaration says START 1 INCREMENT 1 and the highest id so far is four. So the new row should be five. Let's look.

Query
SELECT ID, LABEL FROM REMOVE_T106 ORDER BY ID;
Result4 rows · 2 columns
IDLABEL
1alpha
3gamma
4delta
101epsilon

A hundred and one. Not five. I did not ask for that and nothing warned me about it.

Let's count the table rather than read it, so there is no arguing about the shape.

Query
SELECT COUNT(*) AS ROWS_PRESENT,
       MIN(ID)  AS LOWEST_ID,
       MAX(ID)  AS HIGHEST_ID
FROM REMOVE_T106;
Result1 row · 3 columns
ROWS_PRESENTLOWEST_IDHIGHEST_ID
41101

Four rows, the lowest id is one, the highest is a hundred and one. Snowflake hands these values out in blocks, and each statement takes a new block rather than carrying on from where the last one stopped. Episode 111 finds exactly the same behaviour in a SEQUENCE.

What that actually means

An AUTOINCREMENT id is not a row count, and it never was. If anything in your reporting uses MAX(ID) to mean “how many rows are there”, this grid is what it has been telling you.
The values are unique and they go upwards. That is all they promise. They are not consecutive and there is no setting that makes them consecutive.

Now let's TRUNCATE the table

Before we remove anything else, let's save the moment. We are going to want to read the table as it stands right now, and the way to do that reliably is to put the timestamp in a session variable first.

Setup
-- Save the moment, before anything is removed.
SET t106_before_truncate = (SELECT CURRENT_TIMESTAMP());
Query
SET t106_before_truncate = (SELECT CURRENT_TIMESTAMP());
Result1 row · 1 column
status
Statement executed successfully.

Now TRUNCATE.

Query
TRUNCATE TABLE REMOVE_T106;
Result1 row · 1 column
status
Statement executed successfully.

Statement executed successfully, and that is all it says. It does not tell us how many rows went.

Query
SELECT COUNT(*) AS ROWS_PRESENT FROM REMOVE_T106;
Result1 row · 1 column
ROWS_PRESENT
0

Zero rows, and the query ran. So the table is still there and it is empty. On that much, TRUNCATE and DELETE look the same from the outside.

So what survived the truncate?

The rows are gone. Let's find out what else went with them. First the columns, with their types, their nullability and their defaults.

Query
SELECT COLUMN_NAME, DATA_TYPE, IS_NULLABLE, COLUMN_DEFAULT
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = 'PUBLIC' AND TABLE_NAME = 'REMOVE_T106'
ORDER BY ORDINAL_POSITION;
Result4 rows · 4 columns
COLUMN_NAMEDATA_TYPEIS_NULLABLECOLUMN_DEFAULT
IDNUMBERYESNULL
LABELTEXTNONULL
GRADETEXTYES'standard'
ADDEDTIMESTAMP_NTZYESCURRENT_TIMESTAMP()

All four columns are still declared. LABEL is still NOT NULL. GRADE still defaults to 'standard' and ADDED still defaults to CURRENT_TIMESTAMP().

Have a look at the COLUMN_DEFAULT cell for ID while we are here. It is a real NULL, which the grid above shows differently from an empty cell. An AUTOINCREMENT column does not record a default in this view at all, which is worth knowing if you ever go looking for one.

Now the table comment.

Query
SELECT TABLE_NAME, COMMENT, ROW_COUNT
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = 'PUBLIC' AND TABLE_NAME = 'REMOVE_T106';
Result1 row · 3 columns
TABLE_NAMECOMMENTROW_COUNT
REMOVE_T106episode 106 probe - dropped at the end of this file0

The comment is there word for word and the row count is zero. So TRUNCATE removed the rows and nothing else.

Did TRUNCATE reset the AUTOINCREMENT counter?

This is the question people bring with them from other databases. In several of them TRUNCATE resets the identity counter and DELETE does not, and that difference is one of the usual reasons for choosing one over the other.

The table is empty. Let's put one row into it and see what id it gets.

Query
INSERT INTO REMOVE_T106 (LABEL) SELECT 'zeta';
Result1 row · 1 column
number of rows inserted
1
Query
SELECT ID, LABEL, GRADE FROM REMOVE_T106 ORDER BY ID;
Result1 row · 3 columns
IDLABELGRADE
201zetastandard

Two hundred and one. Not one. The counter carried on from where it was, through an empty table.

Let's ask that as a single row, so the answer is the result rather than our reading of it.

Query
SELECT MIN(ID)                     AS THE_ONLY_ID,
       IFF(MIN(ID) = 1, 'RESET TO 1', 'KEPT COUNTING') AS THE_VERDICT
FROM REMOVE_T106;
Result1 row · 2 columns
THE_ONLY_IDTHE_VERDICT
201KEPT COUNTING

KEPT COUNTING. So in Snowflake TRUNCATE does not reset an AUTOINCREMENT column, and if you came here expecting it to, that is the assumption to leave behind.

Can we get the truncated rows back?

There is no UNTRUNCATE command in Snowflake. But a TRUNCATE is a change to a table, and Time Travel sees changes to tables.

A word on method first, because it matters more than the query does. The obvious way to look backwards is AT(OFFSET => -60), and in a demo like this it is wrong. The table is seconds old, so sixty seconds ago is before it existed. A smaller offset is worse, because it can land on either side of the TRUNCATE depending on how fast the statements ran. An offset measured in seconds is a race with the clock.

That is why we saved the moment into a session variable earlier. Let's use it.

Query
SELECT ID, LABEL FROM REMOVE_T106 AT(TIMESTAMP => $t106_before_truncate)
ORDER BY ID;
Result4 rows · 2 columns
IDLABEL
1alpha
3gamma
4delta
101epsilon

There they are. The same ids we had before the truncate, read out of the same table by name.

Let's count then and now in one row.

Query
SELECT (SELECT COUNT(*) FROM REMOVE_T106 AT(TIMESTAMP => $t106_before_truncate))
         AS ROWS_BEFORE_THE_TRUNCATE,
       (SELECT COUNT(*) FROM REMOVE_T106)
         AS ROWS_NOW;
Result1 row · 2 columns
ROWS_BEFORE_THE_TRUNCATEROWS_NOW
41

Four rows before the truncate, one row now. Both numbers come from the same table, asked two different ways.

Putting them back is an ordinary INSERT that selects from the older view of the table. No special command at all.

Query
INSERT INTO REMOVE_T106 (LABEL, GRADE)
SELECT LABEL, GRADE FROM REMOVE_T106 AT(TIMESTAMP => $t106_before_truncate);
Result1 row · 1 column
number of rows inserted
4
Query
SELECT ID, LABEL, GRADE FROM REMOVE_T106 ORDER BY ID;
Result5 rows · 3 columns
IDLABELGRADE
201zetastandard
301alphastandard
302gammastandard
303deltastandard
304epsilonstandard

The labels are all back. The ids are not: the recovered rows came in as three hundred and one to three hundred and four, because we inserted LABEL and GRADE and let the counter supply the id again.

The rows came back. The keys did not.

This is the part to think about before you rely on the trick. Time Travel brings back the data. It does not bring back the keys, unless you insert the key column explicitly as well. Anything pointing at the old ids is pointing at nothing.

Now let's DROP the table

The third command takes the table itself.

Query
DROP TABLE REMOVE_T106;
Result1 row · 1 column
status
REMOVE_T106 successfully dropped.

Now let's try to read from it.

Query
SELECT COUNT(*) AS ROWS_PRESENT FROM REMOVE_T106;
Query failed — Snowflake returned an error
002003 (42S02): SQL compilation error:
Object 'REMOVE_T106' does not exist or not authorized. Your primary role ACCOUNTADMIN or one of your secondary roles must have at least one privilege granted on TABLE REMOVE_T106.

002003, object does not exist. This is not an empty table, it is a missing one.

And the catalog?

Query
SELECT COUNT(*) AS ROWS_IN_THE_CATALOG
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = 'PUBLIC' AND TABLE_NAME = 'REMOVE_T106';
Result1 row · 1 column
ROWS_IN_THE_CATALOG
0

Zero. INFORMATION_SCHEMA.TABLES has no row for that name at all. After a DELETE or a TRUNCATE the catalog still describes the table. After a DROP there is nothing to describe.

Let's ask for it back with UNDROP

DROP and UNDROP are a matched pair. One sentence each.

Query
UNDROP TABLE REMOVE_T106;
Result1 row · 1 column
status
Table REMOVE_T106 successfully restored.

Successfully restored. So what came back with it?

Query
SELECT ID, LABEL, GRADE FROM REMOVE_T106 ORDER BY ID;
Result5 rows · 3 columns
IDLABELGRADE
201zetastandard
301alphastandard
302gammastandard
303deltastandard
304epsilonstandard

Five rows, which is exactly what was in the table when we dropped it: the row we inserted after the truncate, and the four we recovered.

Query
SELECT TABLE_NAME, COMMENT
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = 'PUBLIC' AND TABLE_NAME = 'REMOVE_T106';
Result1 row · 2 columns
TABLE_NAMECOMMENT
REMOVE_T106episode 106 probe - dropped at the end of this file

And the comment came back as well. UNDROP restores the object, not just its contents.

Now the part I could not predict: can we UNDROP twice?

Here is the question. If a name has been dropped more than once, with different tables under it each time, does UNDROP walk back through them one at a time?

Let's find out. Drop the table we have, then create a completely different one on the same name, with different columns and a different comment.

Query
DROP TABLE REMOVE_T106;
Result1 row · 1 column
status
REMOVE_T106 successfully dropped.
Query
CREATE OR REPLACE TABLE REMOVE_T106 (
    ID    INT,
    LABEL VARCHAR(30)
)
COMMENT = 'the SECOND table to wear this name';
Result1 row · 1 column
status
Table REMOVE_T106 successfully created.
Query
INSERT INTO REMOVE_T106 (ID, LABEL) SELECT 99, 'second-version-only';
Result1 row · 1 column
number of rows inserted
1
Query
SELECT ID, LABEL FROM REMOVE_T106 ORDER BY ID;
Result1 row · 2 columns
IDLABEL
99second-version-only

One row, and it says second-version-only. Nothing in this table came from the first one.

Now drop this one too. The name has now been dropped twice, with different data under it each time.

Query
DROP TABLE REMOVE_T106;
Result1 row · 1 column
status
REMOVE_T106 successfully dropped.
Query
UNDROP TABLE REMOVE_T106;
Result1 row · 1 column
status
Table REMOVE_T106 successfully restored.

Restored. Which one came back?

Query
SELECT ID, LABEL FROM REMOVE_T106 ORDER BY ID;
Result1 row · 2 columns
IDLABEL
99second-version-only
Query
SELECT TABLE_NAME, COMMENT
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = 'PUBLIC' AND TABLE_NAME = 'REMOVE_T106';
Result1 row · 2 columns
TABLE_NAMECOMMENT
REMOVE_T106the SECOND table to wear this name

The second one, with its own comment. The most recent table to wear the name is the one that comes back.

Query
SELECT ID, LABEL FROM REMOVE_T106 ORDER BY ID;
Result1 row · 2 columns
IDLABEL
99second-version-only
Query
SELECT COUNT(*) AS TABLES_WITH_THIS_NAME
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = 'PUBLIC' AND TABLE_NAME = 'REMOVE_T106';
Result1 row · 1 column
TABLES_WITH_THIS_NAME
1

One table on the name, holding the second version's row. So far nothing surprising. The question is what happens when we ask again.

So let's UNDROP again

A word about the name before the next grid, because it changes. When this demo first ran I genuinely did not know the answer, so the second UNDROP went into the script unmarked, and the capture harness of that evening stored nothing for an unmarked failure. The message was lost. The harness was fixed the same night and a follow-up file asked the question again with the right marker, on a table called REMOVE_T106B. That is where the grids below come from, and why the name has a B on the end.

Same setup as before. A first table on the name, with a row in it.

Setup
-- The follow-up run, on a name of its own.
CREATE OR REPLACE TABLE REMOVE_T106B (ID INT, LABEL VARCHAR(30))
    COMMENT = 'the FIRST table to wear this name';

INSERT INTO REMOVE_T106B (ID, LABEL) SELECT 1, 'first-version-only';
Query
CREATE OR REPLACE TABLE REMOVE_T106B (ID INT, LABEL VARCHAR(30))
COMMENT = 'the FIRST table to wear this name';
Result1 row · 1 column
status
Table REMOVE_T106B successfully created.
Query
INSERT INTO REMOVE_T106B (ID, LABEL) SELECT 1, 'first-version-only';
Result1 row · 1 column
number of rows inserted
1
Query
SELECT ID, LABEL FROM REMOVE_T106B ORDER BY ID;
Result1 row · 2 columns
IDLABEL
1first-version-only

Now drop it, and build a different table on the same name.

Query
DROP TABLE REMOVE_T106B;
Query
CREATE OR REPLACE TABLE REMOVE_T106B (ID INT, LABEL VARCHAR(30))
COMMENT = 'the SECOND table to wear this name';
Result1 row · 1 column
status
Table REMOVE_T106B successfully created.
Query
INSERT INTO REMOVE_T106B (ID, LABEL) SELECT 99, 'second-version-only';
Result1 row · 1 column
number of rows inserted
1
Query
SELECT ID, LABEL FROM REMOVE_T106B ORDER BY ID;
Result1 row · 2 columns
IDLABEL
99second-version-only

Drop that one too, and ask for it back, exactly as we did a moment ago.

Query
DROP TABLE REMOVE_T106B;

UNDROP TABLE REMOVE_T106B;

That restored the second version, the same as before. Now the question. Let's run UNDROP a second time and see whether the first table comes back underneath it.

Query
UNDROP TABLE REMOVE_T106B;
Query failed — Snowflake returned an error
002002 (42710): SQL compilation error:
Object 'REMOVE_T106B' already exists.

Refused, and read the message carefully, because it is not the refusal I expected. It does not say there is nothing left to restore. It says “Object 'REMOVE_T106B' already exists.”

That is the mechanism. UNDROP restores an object to its name, and the name is occupied, so there is nowhere to put anything. UNDROP is not a stack you can pop twice.

Query
SELECT (SELECT COUNT(*) FROM INFORMATION_SCHEMA.TABLES
        WHERE TABLE_SCHEMA = 'PUBLIC' AND TABLE_NAME = 'REMOVE_T106B')
         AS TABLES_WEARING_THIS_NAME,
       (SELECT COUNT(*) FROM REMOVE_T106B WHERE LABEL = 'first-version-only')
         AS ROWS_FROM_THE_FIRST_VERSION,
       (SELECT COUNT(*) FROM REMOVE_T106B WHERE LABEL = 'second-version-only')
         AS ROWS_FROM_THE_SECOND_VERSION;
Result1 row · 3 columns
TABLES_WEARING_THIS_NAMEROWS_FROM_THE_FIRST_VERSIONROWS_FROM_THE_SECOND_VERSION
101

One table wearing the name, zero rows from the first version in it, one row from the second. That is the state we are left in.

Can Time Travel reach the older table?

This is the obvious next thing to try, and I want to be careful about what the answer shows. The query asks the same name for how it looked one second ago.

Query
SELECT ID, LABEL FROM REMOVE_T106B AT(OFFSET => -1) ORDER BY ID;
Result1 row · 2 columns
IDLABEL
99second-version-only

The second version again.

What this grid does not settle

That grid does not answer the question, and I am not going to pretend it does. One second before this statement ran, the name was already held by the second version — it had been created, filled, dropped and restored moments earlier. So this offset was always going to return the second version, whichever way the real answer falls.
It is the same mistake the truncate section above warns about: an offset measured in seconds is a race with the clock. If you want to test this yourself, use a captured timestamp from before the first table was dropped, the way we did with $t106_before_truncate.

What this page does settle is the refusal above, and it is the part worth carrying away. While a table is sitting on a name, UNDROP on that name is refused, and the message is about the name rather than about the history. So the ordinary habit of writing CREATE OR REPLACE over a name, then noticing a mistake, then reaching for UNDROP, does not work the way you would hope.

Now let's measure all three on the same table

We have been going one command at a time on a table that kept changing. Let's do the plain comparison on a fresh table instead, asking the same two questions after each removal: are the rows there, and is the table in the catalog.

Query
CREATE OR REPLACE TABLE MEASURE_T106 (ID INT, LABEL VARCHAR(20));
Result1 row · 1 column
status
Table MEASURE_T106 successfully created.
Query
INSERT INTO MEASURE_T106 (ID, LABEL) SELECT 1, 'one'
UNION ALL SELECT 2, 'two'
UNION ALL SELECT 3, 'three';
Result1 row · 1 column
number of rows inserted
3
Query
SELECT (SELECT COUNT(*) FROM MEASURE_T106) AS ROWS_PRESENT,
       (SELECT COUNT(*) FROM INFORMATION_SCHEMA.TABLES
        WHERE TABLE_SCHEMA = 'PUBLIC' AND TABLE_NAME = 'MEASURE_T106')
                                           AS TABLE_IN_CATALOG;
Result1 row · 2 columns
ROWS_PRESENTTABLE_IN_CATALOG
31

Three rows present, and the table is in the catalog. That is the starting point.

After a DELETE of everything

Query
DELETE FROM MEASURE_T106;
Result1 row · 1 column
number of rows deleted
3
Query
SELECT (SELECT COUNT(*) FROM MEASURE_T106) AS ROWS_PRESENT,
       (SELECT COUNT(*) FROM INFORMATION_SCHEMA.TABLES
        WHERE TABLE_SCHEMA = 'PUBLIC' AND TABLE_NAME = 'MEASURE_T106')
                                           AS TABLE_IN_CATALOG;
Result1 row · 2 columns
ROWS_PRESENTTABLE_IN_CATALOG
01

No rows, table still there.

After a TRUNCATE

Query
INSERT INTO MEASURE_T106 (ID, LABEL) SELECT 1, 'one'
UNION ALL SELECT 2, 'two'
UNION ALL SELECT 3, 'three';
Result1 row · 1 column
number of rows inserted
3
Query
TRUNCATE TABLE MEASURE_T106;
Result1 row · 1 column
status
Statement executed successfully.
Query
SELECT (SELECT COUNT(*) FROM MEASURE_T106) AS ROWS_PRESENT,
       (SELECT COUNT(*) FROM INFORMATION_SCHEMA.TABLES
        WHERE TABLE_SCHEMA = 'PUBLIC' AND TABLE_NAME = 'MEASURE_T106')
                                           AS TABLE_IN_CATALOG;
Result1 row · 2 columns
ROWS_PRESENTTABLE_IN_CATALOG
01

The same two numbers. On this measurement DELETE of everything and TRUNCATE are indistinguishable.

After a DROP

Query
DROP TABLE MEASURE_T106;
Result1 row · 1 column
status
MEASURE_T106 successfully dropped.
Query
SELECT (SELECT COUNT(*) FROM INFORMATION_SCHEMA.TABLES
        WHERE TABLE_SCHEMA = 'PUBLIC' AND TABLE_NAME = 'MEASURE_T106')
         AS TABLE_IN_CATALOG,
       (SELECT COUNT(*) FROM INFORMATION_SCHEMA.TABLES
        WHERE TABLE_SCHEMA = 'PUBLIC' AND TABLE_NAME = 'REMOVE_T106')
         AS THE_OTHER_PROBE_STILL_THERE;
Result1 row · 2 columns
TABLE_IN_CATALOGTHE_OTHER_PROBE_STILL_THERE
01

The table is gone from the catalog, and the second column confirms the other probe table is still there, so the DROP took what we asked it to take and nothing more.

The three of them in one line each

DELETE takes the rows you name and is ordinary DML, so it can be part of a transaction.
TRUNCATE takes every row and is DDL.
DROP takes the object, and the catalog stops mentioning it.

One last thing: what each of these says when the table is not there

These four messages are worth seeing once, because you will meet them in a deploy script at some point.

First, dropping a table that does not exist.

Query
DROP TABLE NO_SUCH_TABLE_T106;
Query failed — Snowflake returned an error
002003 (42S02): SQL compilation error:
Table 'DEMO_DB.PUBLIC.NO_SUCH_TABLE_T106' does not exist or not authorized. Your primary role ACCOUNTADMIN or one of your secondary roles must have at least one privilege granted on TABLE DEMO_DB.PUBLIC.NO_SUCH_TABLE_T106.

An error, which is often not what a re-runnable script wants. So let's add IF EXISTS and ask for the same missing table again.

Query
DROP TABLE IF EXISTS NO_SUCH_TABLE_T106;
Result1 row · 1 column
status
Drop statement executed successfully (NO_SUCH_TABLE_T106 already dropped).

Cheerful about it. The statement succeeds and tells us the table was already dropped.

Now TRUNCATE on the same missing table.

Query
TRUNCATE TABLE NO_SUCH_TABLE_T106;
Query failed — Snowflake returned an error
002003 (42S02): SQL compilation error:
Table 'DEMO_DB.PUBLIC.NO_SUCH_TABLE_T106' does not exist or not authorized. Your primary role ACCOUNTADMIN or one of your secondary roles must have at least one privilege granted on TABLE DEMO_DB.PUBLIC.NO_SUCH_TABLE_T106.

The same shape of error as the bare DROP.

And UNDROP on something that was never there.

Query
UNDROP TABLE NO_SUCH_TABLE_T106;
Query failed — Snowflake returned an error
090025 (02000): Table NO_SUCH_TABLE_T106 did not exist or was purged.

090025, and the wording is worth reading: “did not exist or was purged”. One message for two different situations, so it does not tell you which of them you are in.

Finally, let's clean up after ourselves.

Cleanup
-- Put the schema back the way we found it.
DROP TABLE IF EXISTS REMOVE_T106;
DROP TABLE IF EXISTS MEASURE_T106;
DROP TABLE IF EXISTS REMOVE_T106B;
Query
SELECT CURRENT_DATABASE()                 AS THE_DATABASE,
       CURRENT_SCHEMA()                   AS THE_SCHEMA,
       (SELECT COUNT(*) FROM INFORMATION_SCHEMA.TABLES
        WHERE RIGHT(TABLE_NAME, 5) = '_T106') AS PROBE_TABLES_LEFT,
       (SELECT COUNT(*) FROM CUSTOMERS)   AS DEMO_DB_IS_READABLE;
Result1 row · 4 columns
THE_DATABASETHE_SCHEMAPROBE_TABLES_LEFTDEMO_DB_IS_READABLE
DEMO_DBPUBLIC010
Result1 row · 4 columns
THE_DATABASETHE_SCHEMAPROBE_TABLES_LEFTDEMO_DB_IS_READABLE
DEMO_DBPUBLIC010

No probe tables left from either run, and the demo database still reads. Back where we started.

Key points

  • DELETE takes the rows you name. TRUNCATE takes every row. DROP takes the table. After the first two the table is still in the catalog, after the third it is not.
  • TRUNCATE kept every column, the NOT NULL, both defaults and the table comment. Only the rows went.
  • TRUNCATE does not reset an AUTOINCREMENT column. The next row came in at two hundred and one.
  • The counter had already jumped from four to a hundred and one on its own, because Snowflake hands these values out in blocks and each statement takes a new block.
  • So an AUTOINCREMENT id is not a row count. Nothing should use MAX(ID) to mean “how many”.
  • There is no UNTRUNCATE, and there does not need to be. Time Travel had the rows and an ordinary INSERT put them back.
  • But the recovered rows got new ids, because the ids came from the counter again. The data came back and the keys did not.
  • An offset measured in seconds is a race with the clock in a fast script. Capture the timestamp into a session variable and use that as the anchor.
  • UNDROP brought back the rows and the comment together.
  • UNDROP is not a stack. Drop a name twice and the most recent table is the one that returns.
  • A second UNDROP is refused with 002002, object already exists — the refusal is about the name being occupied, not about the history being empty.
  • DROP TABLE IF EXISTS on a missing table succeeds and says already dropped. A bare DROP and a TRUNCATE both error. UNDROP of something never dropped says did not exist or was purged.
Next in this series

Episode 107 — CREATE OR ALTER TABLE. The statement that keeps your data where CREATE OR REPLACE throws it away, and the thing it does to a column you leave out of the text.

Every query and every result grid on this page was captured from a live Snowflake account (version 10.34.101) running the demo script for this episode. Two statements appear as plain code with no grid, and the text says so where they appear: the DROP and UNDROP steps of the follow-up run, whose capture names collide with the first run's and would show the wrong table. One grid on this page does not support the claim the spoken script makes about it, and the warning beside it says which one and why. Every count in the text is read off one of the grids on this page. Nothing is timed; the Time Travel anchor is a captured timestamp, not a delay. The _T106 tables are created and dropped by the scripts above. Behaviour follows the Snowflake DROP TABLE, UNDROP TABLE and TRUNCATE TABLE documentation.

No comments:

Post a Comment

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