In this post we are going to cover time travel in Snowflake, with AT and BEFORE.
Time travel is not a backup. It is the same table, read as of a moment that has already passed. You write an ordinary SELECT and add a clause naming the moment you want.
There are three ways of naming that moment, and they are not interchangeable. We will start by breaking a table on purpose and then build the three ways up step by step. Every query below was run on a real Snowflake account, and every result you see is the output it gave back.
Episode 132 of the Snowflake SQL: Zero to Hero series on TechBrothersIT.
- Let's create some sample data
- First, can a session variable hold a statement id?
- Now let's do some damage
- Let's read the table before the delete
- So let's pick the right statement
- What is the difference between AT and BEFORE?
- Now the query everybody actually wants
- Let's try to repair it
- Now let's name the moment a different way, with OFFSET
- What happens with an offset in the future?
- And the third way: a wall clock timestamp
- Can we build a table out of the past?
- All of this depends on retention, so what do we have?
- What happens when retention is zero?
- And what else it refuses
- One last thing: the teardown
Let's create some sample data
We need a small table with something in it that we can damage and then try to get back.
-- Sample data for this post.
-- A small table we are going to damage on purpose.
USE DATABASE DEMO_DB;
USE SCHEMA PUBLIC;
CREATE OR REPLACE TABLE SALES_T132 (
SALE_ID INT,
REGION VARCHAR(10),
AMOUNT NUMBER(10,2)
);
INSERT INTO SALES_T132 (SALE_ID, REGION, AMOUNT)
VALUES (1, 'north', 100.00), (2, 'north', 250.50),
(3, 'south', 75.25), (4, 'south', 310.00),
(5, 'east', 45.00), (6, 'east', 88.25);SELECT SALE_ID AS SALE_ID, REGION AS REGION, AMOUNT AS AMOUNT
FROM SALES_T132
ORDER BY SALE_ID;| SALE_ID | REGION | AMOUNT |
|---|---|---|
| 1 | north | 100.00 |
| 2 | north | 250.50 |
| 3 | south | 75.25 |
| 4 | south | 310.00 |
| 5 | east | 45.00 |
| 6 | east | 88.25 |
Six rows, three regions, and an amount on each one.
SELECT COUNT(*) AS ROWS_IN_THE_TABLE,
SUM(AMOUNT) AS TOTAL_AMOUNT
FROM SALES_T132;| ROWS_IN_THE_TABLE | TOTAL_AMOUNT |
|---|---|
| 6 | 869.00 |
Six rows and 869.00. Those are the two numbers we are going to be checking against for the rest of this post.
First, can a session variable hold a statement id?
Before anything else we need to settle this one, because if the answer is no then none of what follows is usable from a script.
One of the three ways to name a moment is by the statement that made it. That means getting hold of a query id and keeping it somewhere.
SET QID_INSERT = LAST_QUERY_ID();| status |
|---|
| Statement executed successfully. |
SELECT $QID_INSERT AS THE_INSERT_QUERY_ID;| THE_INSERT_QUERY_ID |
|---|
| 01c77223-0308-b861-0010-ea6e000aa202 |
A query id, held in a session variable. Whether time travel will accept the variable rather than a literal is a different question, and we will find out in two sections' time.
Now let's do some damage
Somebody updates the wrong rows. Everything in the south region goes to zero.
UPDATE SALES_T132 SET AMOUNT = 0 WHERE REGION = 'south';| number of rows updated | number of multi-joined rows updated |
|---|---|
| 2 | 0 |
SET QID_UPDATE = LAST_QUERY_ID();| status |
|---|
| Statement executed successfully. |
Two rows updated. Then somebody deletes two more.
DELETE FROM SALES_T132 WHERE SALE_ID IN (5, 6);| number of rows deleted |
|---|
| 2 |
SET QID_DELETE = LAST_QUERY_ID();| status |
|---|
| Statement executed successfully. |
So we have three anchors now, one for each statement: the insert, the update and the delete. Three moments we can ask for by name.
And this is the table we are left with.
SELECT SALE_ID AS SALE_ID, REGION AS REGION, AMOUNT AS AMOUNT
FROM SALES_T132
ORDER BY SALE_ID;| SALE_ID | REGION | AMOUNT |
|---|---|---|
| 1 | north | 100.00 |
| 2 | north | 250.50 |
| 3 | south | 0.00 |
| 4 | south | 0.00 |
Four rows. Sale ids three and four are zero, and five and six have gone altogether.
SELECT COUNT(*) AS ROWS_IN_THE_TABLE,
SUM(AMOUNT) AS TOTAL_AMOUNT
FROM SALES_T132;| ROWS_IN_THE_TABLE | TOTAL_AMOUNT |
|---|---|
| 4 | 350.50 |
Four rows and 350.50, where it was six rows and 869.00.
Let's read the table before the delete
The obvious first move is to ask for the table as it was immediately before the delete, using the anchor we kept.
SELECT SALE_ID AS SALE_ID, REGION AS REGION, AMOUNT AS AMOUNT
FROM SALES_T132 BEFORE(STATEMENT => $QID_DELETE)
ORDER BY SALE_ID;| SALE_ID | REGION | AMOUNT |
|---|---|---|
| 1 | north | 100.00 |
| 2 | north | 250.50 |
| 3 | south | 0.00 |
| 4 | south | 0.00 |
| 5 | east | 45.00 |
| 6 | east | 88.25 |
Two things just happened. The session variable was accepted, which answers the question we opened with. And all six rows are back.
Now let's count it properly, because the row count is not the whole story.
SELECT COUNT(*) AS ROWS_IN_THE_TABLE,
SUM(AMOUNT) AS TOTAL_AMOUNT
FROM SALES_T132 BEFORE(STATEMENT => $QID_DELETE);| ROWS_IN_THE_TABLE | TOTAL_AMOUNT |
|---|---|
| 6 | 483.75 |
Six rows, and 483.75. Not 869.00.
Look at the grid above again. Sale ids five and six are back with their real amounts, and three and four are still zero.
Of course they are. Before the delete is after the update. The two statements happened in that order and time travel is honest about it.
Before the delete is not before everything. A row count that looks right is not a table that is right, and this grid is the proof. You have to pick the statement you actually mean.
So let's pick the right statement
Let's ask for the moment before the update instead.
SELECT SALE_ID AS SALE_ID, REGION AS REGION, AMOUNT AS AMOUNT
FROM SALES_T132 BEFORE(STATEMENT => $QID_UPDATE)
ORDER BY SALE_ID;| SALE_ID | REGION | AMOUNT |
|---|---|---|
| 1 | north | 100.00 |
| 2 | north | 250.50 |
| 3 | south | 75.25 |
| 4 | south | 310.00 |
| 5 | east | 45.00 |
| 6 | east | 88.25 |
SELECT COUNT(*) AS ROWS_IN_THE_TABLE,
SUM(AMOUNT) AS TOTAL_AMOUNT
FROM SALES_T132 BEFORE(STATEMENT => $QID_UPDATE);| ROWS_IN_THE_TABLE | TOTAL_AMOUNT |
|---|---|
| 6 | 869.00 |
Six rows and 869.00. That is the table we started with, down to the total.
What is the difference between AT and BEFORE?
It is exactly one statement, and the insert is the easiest place to see it.
Let's ask for the table AT the insert.
SELECT COUNT(*) AS ROWS_IN_THE_TABLE,
SUM(AMOUNT) AS TOTAL_AMOUNT
FROM SALES_T132 AT(STATEMENT => $QID_INSERT);| ROWS_IN_THE_TABLE | TOTAL_AMOUNT |
|---|---|
| 6 | 869.00 |
Six rows and 869.00. The insert is included.
Now the same anchor with BEFORE.
SELECT COUNT(*) AS ROWS_IN_THE_TABLE
FROM SALES_T132 BEFORE(STATEMENT => $QID_INSERT);| ROWS_IN_THE_TABLE |
|---|
| 0 |
Zero rows. The insert is excluded, and before the insert this table was empty.
AT includes the statement you name.BEFORE excludes it.
That is the whole distinction, and it is the one to get right when you are pointing at the statement that did the damage.
Now the query everybody actually wants
When something has gone wrong, what you want is not the old table or the new table. It is both of them side by side, with a verdict on every row.
A time travel query is just a table expression, so we can join the table to its own past with a full outer join.
SELECT COALESCE(o.SALE_ID, n.SALE_ID) AS SALE_ID,
o.AMOUNT AS AMOUNT_BEFORE,
n.AMOUNT AS AMOUNT_NOW,
CASE WHEN n.SALE_ID IS NULL THEN 'DELETED'
WHEN o.AMOUNT <> n.AMOUNT THEN 'CHANGED'
ELSE 'same' END AS WHAT_HAPPENED
FROM SALES_T132 BEFORE(STATEMENT => $QID_UPDATE) o
FULL OUTER JOIN SALES_T132 n ON n.SALE_ID = o.SALE_ID
ORDER BY SALE_ID;| SALE_ID | AMOUNT_BEFORE | AMOUNT_NOW | WHAT_HAPPENED |
|---|---|---|---|
| 1 | 100.00 | 100.00 | same |
| 2 | 250.50 | 250.50 | same |
| 3 | 75.25 | 0.00 | CHANGED |
| 4 | 310.00 | 0.00 | CHANGED |
| 5 | 45.00 | NULL | DELETED |
| 6 | 88.25 | NULL | DELETED |
Six rows, and every one of them labelled. One and two are the same on both sides. Three and four changed. Five and six are deleted, and their AMOUNT_NOW is NULL because the full outer join had nothing on the right to match them with.
That is the grid you want at two in the morning. It tells you what to put back and what to correct, separately.
Let's try to repair it
The rows that are missing can be read out of the past and inserted straight back in.
INSERT INTO SALES_T132 (SALE_ID, REGION, AMOUNT)
SELECT SALE_ID, REGION, AMOUNT
FROM SALES_T132 BEFORE(STATEMENT => $QID_UPDATE)
WHERE SALE_ID NOT IN (SELECT SALE_ID FROM SALES_T132);| number of rows inserted |
|---|
| 2 |
Two rows inserted. Let's check the table.
SELECT COUNT(*) AS ROWS_IN_THE_TABLE,
SUM(AMOUNT) AS TOTAL_AMOUNT
FROM SALES_T132;| ROWS_IN_THE_TABLE | TOTAL_AMOUNT |
|---|---|
| 6 | 483.75 |
Six rows again. And 483.75, not 869.00.
So that is not a fix, and it stays in the post because of it. The deleted rows came back. The update was never undone.
Look at the WHERE clause in the insert above. It only asked for sale ids that were missing from the live table. Three and four were not missing. They were there, and wrong.
The row count said six and we nearly stopped reading. The total is what caught it. That is why every check in this course has two numbers in it rather than one.
Now let's name the moment a different way, with OFFSET
STATEMENT is one of the three ways. OFFSET is the second, and it counts backwards in seconds from now.
Which means it needs some seconds of history to point at, so the script waits before asking.
SELECT SYSTEM$WAIT(20) AS WAITED;| WAITED |
|---|
| waited 20 seconds |
That is a wait, not a measurement. Nothing in this course is timed and no performance claim is being made with it.
SELECT COUNT(*) AS ROWS_IN_THE_TABLE,
SUM(AMOUNT) AS TOTAL_AMOUNT
FROM SALES_T132 AT(OFFSET => -15);| ROWS_IN_THE_TABLE | TOTAL_AMOUNT |
|---|---|
| 6 | 483.75 |
Six rows and 483.75, which is the table as our half-repair left it.
SELECT COUNT(*) AS ROWS_IN_THE_TABLE,
SUM(AMOUNT) AS TOTAL_AMOUNT
FROM SALES_T132 AT(OFFSET => -1);| ROWS_IN_THE_TABLE | TOTAL_AMOUNT |
|---|---|
| 6 | 483.75 |
The same answer, because nothing has changed in between.
And that is the thing to understand about OFFSET. It is relative to the moment you run it. Run the same query in an hour and it means something completely different.
What happens with an offset in the future?
A negative offset goes backwards, so a positive one is worth trying.
SELECT COUNT(*) AS ROWS_IN_THE_TABLE
FROM SALES_T132 AT(OFFSET => 60);002038 (22000): SQL compilation error: Invalid data type [60] in AT(OFFSET => 60)
Refused. Invalid data type [60] in AT(OFFSET => 60), which is an odd way to say that a moment has not happened yet. But it is refused, which is the important part.
Now an offset that goes further back than this table's history allows. Ten days, in seconds.
SELECT COUNT(*) AS ROWS_IN_THE_TABLE
FROM SALES_T132 AT(OFFSET => -864000);000707 (02000): Time travel data is not available for table SALES_T132. The requested time is either beyond the allowed time travel period or before the object creation time.
Time travel data is not available for table SALES_T132. Read the rest of that sentence too, because it names two different reasons and does not say which one applies. We are going to see the same message again later for a quite different cause.
And the third way: a wall clock timestamp
The third way of naming a moment is the one you would write if a person told you when something broke.
SELECT COUNT(*) AS ROWS_IN_THE_TABLE,
SUM(AMOUNT) AS TOTAL_AMOUNT
FROM SALES_T132 AT(TIMESTAMP => DATEADD(SECOND, -15, CURRENT_TIMESTAMP()));| ROWS_IN_THE_TABLE | TOTAL_AMOUNT |
|---|---|
| 6 | 483.75 |
Six rows and 483.75, the same answer the offset gave us, asked for in a different way.
Can we build a table out of the past?
A time travel query can be used anywhere a query can, which includes the SELECT inside a CREATE TABLE AS.
CREATE OR REPLACE TABLE RECOVERED_T132 AS
SELECT SALE_ID, REGION, AMOUNT
FROM SALES_T132 BEFORE(STATEMENT => $QID_UPDATE);| status |
|---|
| Table RECOVERED_T132 successfully created. |
SELECT COUNT(*) AS ROWS_IN_THE_TABLE,
SUM(AMOUNT) AS TOTAL_AMOUNT
FROM RECOVERED_T132;| ROWS_IN_THE_TABLE | TOTAL_AMOUNT |
|---|---|
| 6 | 869.00 |
Six rows and 869.00. A clean copy of the old version, as a real table, which you can compare against the live one at your own pace.
On a table you have just damaged, this is usually a calmer move than repairing in place.
All of this depends on retention, so what do we have?
Time travel only reaches back as far as the table's retention period. The catalog will tell us what this one has.
SELECT TABLE_NAME AS THE_TABLE,
TABLE_TYPE AS THE_TYPE,
IS_TRANSIENT AS IS_IT_TRANSIENT,
RETENTION_TIME AS RETENTION_DAYS
FROM INFORMATION_SCHEMA.TABLES
WHERE RIGHT(TABLE_NAME, 5) = '_T132'
ORDER BY THE_TABLE;| THE_TABLE | THE_TYPE | IS_IT_TRANSIENT | RETENTION_DAYS |
|---|---|---|---|
| SALES_T132 | BASE TABLE | NO | 1 |
A base table, not transient, with one day. One day is the default on a standard account.
Now let's make a transient table, which is the cheaper kind, and ask the same question of it.
CREATE OR REPLACE TRANSIENT TABLE TRANS_T132 (SALE_ID INT, AMOUNT NUMBER(10,2));| status |
|---|
| Table TRANS_T132 successfully created. |
INSERT INTO TRANS_T132 (SALE_ID, AMOUNT) VALUES (1, 10.00);| number of rows inserted |
|---|
| 1 |
SELECT TABLE_NAME AS THE_TABLE,
IS_TRANSIENT AS IS_IT_TRANSIENT,
RETENTION_TIME AS RETENTION_DAYS
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_NAME = 'TRANS_T132';| THE_TABLE | IS_IT_TRANSIENT | RETENTION_DAYS |
|---|---|---|
| TRANS_T132 | YES | 1 |
Also one day. So far the two of them look the same.
Let's raise the transient one to three days.
ALTER TABLE TRANS_T132 SET DATA_RETENTION_TIME_IN_DAYS = 3;001008 (22023): SQL compilation error: invalid value [3] for parameter 'DATA_RETENTION_TIME_IN_DAYS'
invalid value [3] for parameter 'DATA_RETENTION_TIME_IN_DAYS'. And that message does not tell you why three is invalid.
Now the same statement on the permanent table.
ALTER TABLE SALES_T132 SET DATA_RETENTION_TIME_IN_DAYS = 3;| status |
|---|
| Statement executed successfully. |
Accepted, with no complaint. Let's put the two of them side by side.
SELECT TABLE_NAME AS THE_TABLE,
IS_TRANSIENT AS IS_IT_TRANSIENT,
RETENTION_TIME AS RETENTION_DAYS
FROM INFORMATION_SCHEMA.TABLES
WHERE RIGHT(TABLE_NAME, 5) = '_T132'
ORDER BY THE_TABLE;| THE_TABLE | IS_IT_TRANSIENT | RETENTION_DAYS |
|---|---|---|
| SALES_T132 | NO | 3 |
| TRANS_T132 | YES | 1 |
Three days and one day. The same statement, two different answers, and the only difference between the tables is that one of them is transient.
A transient table cannot go past one day. The error we got never says that, so it is worth writing down.
And a retention that really is too large, on the permanent table.
ALTER TABLE SALES_T132 SET DATA_RETENTION_TIME_IN_DAYS = 9999;001048 (22023): SQL compilation error: Exceeds maximum allowable retention time (90 day(s)).
Exceeds maximum allowable retention time (90 day(s)). That one explains itself properly, which makes the transient message look worse by comparison.
What happens when retention is zero?
Zero is allowed, and it turns time travel off.
ALTER TABLE TRANS_T132 SET DATA_RETENTION_TIME_IN_DAYS = 0;| status |
|---|
| Statement executed successfully. |
Accepted. Now let's ask that table for its past.
SELECT COUNT(*) AS ROWS_IN_THE_TABLE
FROM TRANS_T132 AT(OFFSET => -5);000707 (02000): Time travel data is not available for table TRANS_T132. The requested time is either beyond the allowed time travel period or before the object creation time.
The same code and the same sentence we got when we asked the sales table for ten days back, with a different table name in it. The two error panes are worth comparing.
Be careful about what this one grid proves on its own. The message names two reasons without choosing between them: beyond the allowed period, or before the table was created. We created this transient table a few statements earlier in the same script and then asked it for five seconds ago, so the second reason may apply here too. Nothing captured in this episode separates the two, so we are not going to claim this grid as proof of what retention zero does on its own.
What it does show is useful anyway. A table with time travel switched off and a moment that is simply too far back give you the same message, so the message cannot tell you which of those you are looking at.
And what else it refuses
First, both keywords in one statement.
SELECT COUNT(*) AS ROWS_IN_THE_TABLE
FROM SALES_T132 AT(OFFSET => -5) BEFORE(STATEMENT => $QID_UPDATE);001003 (42000): SQL compilation error: syntax error line 2 at position 50 unexpected '=>'.
A syntax error. You name one moment, not two.
Then a statement id that is not a statement id.
SELECT COUNT(*) AS ROWS_IN_THE_TABLE
FROM SALES_T132 BEFORE(STATEMENT => 'not-a-query-id');000709 (02000): Statement not-a-query-id not found
Statement not-a-query-id not found, which is a clear message with its own code.
And time travel on a table that is not there.
SELECT COUNT(*) AS ROWS_IN_THE_TABLE
FROM NO_SUCH_TABLE_T132 AT(OFFSET => -5);002003 (42S02): SQL compilation error: Object 'NO_SUCH_TABLE_T132' 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 NO_SUCH_TABLE_T132.
The ordinary object-does-not-exist error. The time travel clause never gets a chance to matter.
One last thing: the teardown
We put a retention of three days on the sales table earlier, so let's take that back off before dropping anything.
ALTER TABLE SALES_T132 UNSET DATA_RETENTION_TIME_IN_DAYS;| status |
|---|
| Statement executed successfully. |
DROP TABLE IF EXISTS SALES_T132;| status |
|---|
| SALES_T132 successfully dropped. |
DROP TABLE IF EXISTS TRANS_T132;| status |
|---|
| TRANS_T132 successfully dropped. |
DROP TABLE IF EXISTS RECOVERED_T132;| status |
|---|
| RECOVERED_T132 successfully dropped. |
UNSET (QID_INSERT, QID_UPDATE, QID_DELETE);| status |
|---|
| Statement executed successfully. |
And a check that nothing is left behind.
SELECT CURRENT_DATABASE() AS THE_DATABASE,
CURRENT_SCHEMA() AS THE_SCHEMA,
(SELECT COUNT(*) FROM INFORMATION_SCHEMA.TABLES
WHERE RIGHT(TABLE_NAME, 5) = '_T132') AS PROBE_TABLES_LEFT,
(SELECT COUNT(*) FROM CUSTOMERS) AS DEMO_DB_IS_READABLE;| THE_DATABASE | THE_SCHEMA | PROBE_TABLES_LEFT | DEMO_DB_IS_READABLE |
|---|---|---|---|
| DEMO_DB | PUBLIC | 0 | 10 |
No probe tables left, and the demo database still reads. Back where we started.
Key points
- A session variable holds a query id and time travel accepts it, which is what makes any of this scriptable.
ATincludes the statement you name.BEFOREexcludes it. Before the insert was zero rows and at the insert was six.- Before the delete gave six rows and
483.75, not869.00, because before the delete is after the update. - Pick the statement you actually mean. A restored row count is not a restored table.
- The table full outer joined to its own past gives you a verdict on every row, and a deleted row shows as a
NULLon the live side. - Our repair put the missing rows back and left the wrong ones wrong, because it only looked for missing ids. The total is what caught it.
OFFSETis relative to when you run it, so the same query means something different later.- A positive offset is refused, oddly worded, as an invalid data type.
AT(TIMESTAMP => ...)is the third way, and gave the same answer as the offset.CREATE TABLE AS SELECTworks over a time travel query, which gives you the old version as a real table to compare against.- The default retention is one day. A permanent table goes up to ninety days, and that refusal says so.
- A transient table cannot go past one day, and its refusal does not say so. It only says the value is invalid.
- Asking a table with time travel switched off for its past gives the same message as asking any table for a moment too far back, so the message cannot tell you which it is.
Episode 133 — UNDROP. What retention actually buys you once the whole table is gone, which version comes back when a name has been dropped twice, and a catalog listing that cheerfully shows a table UNDROP says was purged.
Every query and every result grid on this page was captured from a live Snowflake account (version 10.35.101) running the demo script for this episode. The one SYSTEM$WAIT is a wait and not a measurement; nothing in this series is timed. One refusal on this page has two possible causes and the capture cannot separate them, and the warning beside it says which grid and why. Every count in the text is read off one of the grids on this page. Behaviour follows the Snowflake Time Travel documentation.



No comments:
Post a Comment
Note: Only a member of this blog may post a comment.