Snowflake SQL Tutorial 121 - The CREATE TABLE That Committed My Transaction

Snowflake SQL · Episode 121

In this post we are going to cover transactions in Snowflake: BEGIN, COMMIT, ROLLBACK and the AUTOCOMMIT parameter.

A transaction is a group of statements that either all count or none of them do. You open one, you do some work, and then you either keep the work or throw it away.

We will start by reading what the session is already doing, and build it up step by step. On the way we will meet one perfectly ordinary statement that quietly ends the transaction you opened. It is not a DELETE and it is not an error. It is a CREATE TABLE.

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

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

Let's read AUTOCOMMIT before we assume anything

Every statement you have run in this series so far was already inside a transaction. Let's not take that on trust. Let's read the parameter.

SHOW PARAMETERS
SHOW PARAMETERS LIKE 'AUTOCOMMIT' IN SESSION;
Result1 row · 6 columns · scroll →
keyvaluedefaultleveldescriptiontype
AUTOCOMMITtruetrueThe autocommit property determines whether is statement should to be implicitly wrapped within a transaction or not. If autocommit is set to true, then a statement that requires a transaction is executed within a transaction implicitly. If autocommit is off then an explicit commit or rollback is required to close a transaction. The default autocommit value is true.BOOLEAN

Value true, default true. So every statement is wrapped in a transaction of its own and committed the moment it succeeds. The description column spells that out in Snowflake's own words.

That grid is wide. Let's pull out the three columns we care about.

The same answer, tidier
SELECT "key" AS THE_PARAMETER, "value" AS THE_VALUE, "default" AS THE_DEFAULT
FROM TABLE(RESULT_SCAN(LAST_QUERY_ID()));
Result1 row · 3 columns
THE_PARAMETERTHE_VALUETHE_DEFAULT
AUTOCOMMITtruetrue

BEGIN is how we say not this time.

And the function this whole post leans on

CURRENT_TRANSACTION() tells us which transaction we are inside. It is the evidence for every claim below, so let's read it with nothing going on.

Query
SELECT CURRENT_TRANSACTION() AS THE_TRANSACTION_ID;
Result1 row · 1 column
THE_TRANSACTION_ID
NULL

NULL. We are not in a transaction. Inside one it returns an id instead, and that is the difference we will keep checking.

Empty is not NULL

There are two different kinds of blank on this page and they are not the same thing.
The level cell in the SHOW PARAMETERS grid above is an empty string, which is how SHOW output says nothing has overridden the default. The grid marks it empty.
The cell in the grid just above is a real NULL, which is how CURRENT_TRANSACTION() says there is no transaction. The grid prints the word.

Let's create some sample data

Four accounts, with a balance each.

Sample data
-- Sample data for this post. Run it once in a worksheet.
USE DATABASE DEMO_DB;
USE SCHEMA PUBLIC;

CREATE OR REPLACE TABLE ACCOUNTS_T121 (
    ACCOUNT_ID  INT,
    OWNER       VARCHAR(20),
    BALANCE     NUMBER(10,2)
);

INSERT INTO ACCOUNTS_T121 (ACCOUNT_ID, OWNER, BALANCE) VALUES
    (1, 'ana',  500.00),
    (2, 'ben',  120.00),
    (3, 'cleo', 900.00),
    (4, 'dan',   40.00);
Query
SELECT ACCOUNT_ID, OWNER, BALANCE FROM ACCOUNTS_T121 ORDER BY ACCOUNT_ID;
Result4 rows · 3 columns
ACCOUNT_IDOWNERBALANCE
1ana500.00
2ben120.00
3cleo900.00
4dan40.00

Four rows. We are going to move a hundred from ana to ben, which is the oldest example in the book and still the clearest one: two statements that only make sense together.

Let's open a transaction and move some money

BEGIN
BEGIN;
Result1 row · 1 column
status
Statement executed successfully.

Now let's ask the question again.

Query
SELECT CURRENT_TRANSACTION() AS THE_TRANSACTION_ID;
Result1 row · 1 column
THE_TRANSACTION_ID
1790732212756000000

There is an id instead of a NULL. We are inside a transaction.

Now the two halves of the transfer.

Take it out
UPDATE ACCOUNTS_T121 SET BALANCE = BALANCE - 100.00 WHERE ACCOUNT_ID = 1;
Result1 row · 2 columns
number of rows updatednumber of multi-joined rows updated
10
And put it in
UPDATE ACCOUNTS_T121 SET BALANCE = BALANCE + 100.00 WHERE ACCOUNT_ID = 2;
Result1 row · 2 columns
number of rows updatednumber of multi-joined rows updated
10

One row updated each time. UPDATE reports two columns, which is the pair we went through in Episode 117.

What my session sees
SELECT ACCOUNT_ID, OWNER, BALANCE FROM ACCOUNTS_T121 ORDER BY ACCOUNT_ID;
Result4 rows · 3 columns
ACCOUNT_IDOWNERBALANCE
1ana400.00
2ben220.00
3cleo900.00
4dan40.00

Ana is down a hundred and ben is up a hundred. Our own session can see the change. Nobody else can yet, because we have not committed it.

Now let's change our mind and ROLLBACK

ROLLBACK
ROLLBACK;
Result1 row · 1 column
status
Statement executed successfully.
And the transaction
SELECT CURRENT_TRANSACTION() AS THE_TRANSACTION_ID;
Result1 row · 1 column
THE_TRANSACTION_ID
NULL

NULL again. The transaction is closed.

The balances
SELECT ACCOUNT_ID, OWNER, BALANCE FROM ACCOUNTS_T121 ORDER BY ACCOUNT_ID;
Result4 rows · 3 columns
ACCOUNT_IDOWNERBALANCE
1ana500.00
2ben120.00
3cleo900.00
4dan40.00

Exactly as they started. Both updates went, together.

Let's say that in one row rather than reading it off four.

Counted
SELECT SUM(BALANCE) AS TOTAL_BALANCE,
       MAX(IFF(ACCOUNT_ID = 1, BALANCE, NULL)) AS ANAS_BALANCE,
       MAX(IFF(ACCOUNT_ID = 2, BALANCE, NULL)) AS BENS_BALANCE
FROM ACCOUNTS_T121;
Result1 row · 3 columns
TOTAL_BALANCEANAS_BALANCEBENS_BALANCE
1560.00500.00120.00

The total, and the two balances we touched, back where they began.

Now the same transfer again, and this time let's keep it

BEGIN
BEGIN;
Result1 row · 1 column
status
Statement executed successfully.
Take it out
UPDATE ACCOUNTS_T121 SET BALANCE = BALANCE - 100.00 WHERE ACCOUNT_ID = 1;
Result1 row · 2 columns
number of rows updatednumber of multi-joined rows updated
10
And put it in
UPDATE ACCOUNTS_T121 SET BALANCE = BALANCE + 100.00 WHERE ACCOUNT_ID = 2;
Result1 row · 2 columns
number of rows updatednumber of multi-joined rows updated
10
COMMIT
COMMIT;
Result1 row · 1 column
status
Statement executed successfully.
The balances
SELECT ACCOUNT_ID, OWNER, BALANCE FROM ACCOUNTS_T121 ORDER BY ACCOUNT_ID;
Result4 rows · 3 columns
ACCOUNT_IDOWNERBALANCE
1ana400.00
2ben220.00
3cleo900.00
4dan40.00

Four hundred and two twenty, and this time they stay that way.

And a ROLLBACK now does nothing at all, because there is nothing open to roll back.

ROLLBACK
ROLLBACK;
Result1 row · 1 column
status
Statement executed successfully.
Still the same
SELECT ACCOUNT_ID, OWNER, BALANCE FROM ACCOUNTS_T121 ORDER BY ACCOUNT_ID;
Result4 rows · 3 columns
ACCOUNT_IDOWNERBALANCE
1ana400.00
2ben220.00
3cleo900.00
4dan40.00

It reported success and changed nothing. Hold on to that sentence, because the next section is built on it.

Now the one that costs people data

I did not want to assert this one from memory, so the demo file asks it instead, reading CURRENT_TRANSACTION() either side of an ordinary CREATE TABLE.

Where we start
SELECT COUNT(*) AS ROWS_BEFORE FROM ACCOUNTS_T121;
Result1 row · 1 column
ROWS_BEFORE
4
BEGIN
BEGIN;
Result1 row · 1 column
status
Statement executed successfully.
And the transaction
SELECT CURRENT_TRANSACTION() AS THE_TRANSACTION_ID;
Result1 row · 1 column
THE_TRANSACTION_ID
1790732217973000000

There is the id, so we know exactly what we are inside.

Now let's delete something we fully intend to undo.

DELETE
DELETE FROM ACCOUNTS_T121 WHERE BALANCE < 200.00;
Result1 row · 1 column
number of rows deleted
1
Inside the transaction
SELECT COUNT(*) AS ROWS_INSIDE_THE_TRANSACTION FROM ACCOUNTS_T121;
Result1 row · 1 column
ROWS_INSIDE_THE_TRANSACTION
3

One row deleted, three left. The row that went is the only one under the threshold the WHERE clause names.

And now something completely innocent. An audit table. Nothing about this statement touches the accounts.

CREATE TABLE
CREATE OR REPLACE TABLE AUDIT_T121 (
    WHAT_HAPPENED VARCHAR(40)
);
Result1 row · 1 column
status
Table AUDIT_T121 successfully created.

Table created, fine. Now let's read the transaction id again.

And the transaction
SELECT CURRENT_TRANSACTION() AS THE_TRANSACTION_ID;
Result1 row · 1 column
THE_TRANSACTION_ID
NULL

NULL. The transaction is gone, and nothing said so. A DDL statement commits the transaction that was open.

Which means the ROLLBACK we are about to write has nothing left to roll back.

ROLLBACK
ROLLBACK;
Result1 row · 1 column
status
Statement executed successfully.

Statement executed successfully. It reports success, exactly as it did in the previous section when there was nothing open.

And the count
SELECT COUNT(*) AS ROWS_AFTER_THE_ROLLBACK FROM ACCOUNTS_T121;
Result1 row · 1 column
ROWS_AFTER_THE_ROLLBACK
3
Which ones survived
SELECT ACCOUNT_ID, OWNER, BALANCE FROM ACCOUNTS_T121 ORDER BY ACCOUNT_ID;
Result3 rows · 3 columns
ACCOUNT_IDOWNERBALANCE
1ana400.00
2ben220.00
3cleo900.00

Three, not four. The delete stayed deleted, and dan is gone permanently.

The whole trap, in two sentences

The ROLLBACK is not wrong and it is not ignored. It simply arrived after the transaction had already been committed, by a statement that looks like it has nothing to do with the data.
So if you need a CREATE in the middle of a transaction — you do not. Create it before, or create it after. Not in between.

Does a failed statement poison the transaction?

First let's get a fourth row back in the table. The demo file inserts two rows here, one for dan and one for ben, even though only dan was deleted — so from this point the table carries a second ben row. Nothing in the rest of the post looks at ben, so it changes none of the results below, but it is in the grid and worth saying rather than letting you wonder.

INSERT
INSERT INTO ACCOUNTS_T121 (ACCOUNT_ID, OWNER, BALANCE)
VALUES (2, 'ben',  220.00),
       (4, 'dan',   40.00);
Result1 row · 1 column
number of rows inserted
2

Now the real question. In Postgres, a statement that fails inside a transaction aborts it, and everything after it fails too until you roll back. Does Snowflake do that?

BEGIN
BEGIN;
Result1 row · 1 column
status
Statement executed successfully.
One that works
UPDATE ACCOUNTS_T121 SET BALANCE = 777.00 WHERE ACCOUNT_ID = 3;
Result1 row · 2 columns
number of rows updatednumber of multi-joined rows updated
10

Fine. Now one that does not, naming a column that is not there.

One that does not
UPDATE ACCOUNTS_T121 SET NO_SUCH_COLUMN = 1 WHERE ACCOUNT_ID = 3;
Query failed — Snowflake returned an error
000904 (42000): SQL compilation error: error line 1 at position 25
invalid identifier 'NO_SUCH_COLUMN'

Refused, as it should be. So is the transaction still open?

And the transaction
SELECT CURRENT_TRANSACTION() AS THE_TRANSACTION_ID;
Result1 row · 1 column
THE_TRANSACTION_ID
1790732220865000000

The id is still there. It is open. But can it still do work?

Another update
UPDATE ACCOUNTS_T121 SET BALANCE = 888.00 WHERE ACCOUNT_ID = 3;
Result1 row · 2 columns
number of rows updatednumber of multi-joined rows updated
10
And the row
SELECT ACCOUNT_ID, OWNER, BALANCE FROM ACCOUNTS_T121 WHERE ACCOUNT_ID = 3;
Result1 row · 3 columns
ACCOUNT_IDOWNERBALANCE
3cleo888.00

One row updated, and the new value is there inside the transaction. It is perfectly alive. A failed statement does not abort a Snowflake transaction.

Worth checking before you port anything

If you are porting scripts from Postgres, that is a real difference and it runs the dangerous way round. A script that relies on a failure stopping the rest of the transaction will keep going here, and commit the half of the work that succeeded.

What does SHOW TRANSACTIONS report?

While one is open we can list it.

Query
SHOW TRANSACTIONS;
Result1 row · 7 columns · scroll →
idusersessionnamestarted_onstatescope
1790732220865000000TECHBROTHERSITAAMIR476135779492661088bc368b-8156-47a1-b59d-8ae029e68ca72026-09-29 18:37:00.865000-07:00running0

The three columns to read are the id, the name and the state, and the state says running. The grid is wider than that — it also reports the user, the session, when it started and its scope — so scroll sideways if you want the rest.

Now let's roll the whole thing back. Both updates, together, with the failure in between them.

ROLLBACK
ROLLBACK;
Result1 row · 1 column
status
Statement executed successfully.
And the row
SELECT ACCOUNT_ID, OWNER, BALANCE FROM ACCOUNTS_T121 WHERE ACCOUNT_ID = 3;
Result1 row · 3 columns
ACCOUNT_IDOWNERBALANCE
3cleo900.00

Back where it started. The failure changed nothing and neither did the two updates.

What happens when there is nothing open?

Two short ones. A COMMIT with no transaction open, and a ROLLBACK with no transaction open.

COMMIT
COMMIT;
Result1 row · 1 column
status
Statement executed successfully.
ROLLBACK
ROLLBACK;
Result1 row · 1 column
status
Statement executed successfully.

Both quietly accepted. Neither complains, which is convenient in a script and is also exactly why the ROLLBACK after the CREATE TABLE looked like it had worked.

Does BEGIN nest?

Let's open one, read the id, open another one inside it, and read the id again.

BEGIN
BEGIN;
Result1 row · 1 column
status
Statement executed successfully.
The id
SELECT CURRENT_TRANSACTION() AS THE_TRANSACTION_ID;
Result1 row · 1 column
THE_TRANSACTION_ID
1790732223020000000
BEGIN again
BEGIN;
Result1 row · 1 column
status
Statement executed successfully.
The id again
SELECT CURRENT_TRANSACTION() AS THE_TRANSACTION_ID;
Result1 row · 1 column
THE_TRANSACTION_ID
1790732223020000000

The same id came back. It did not nest. The second BEGIN joined the transaction that was already open.

Which means one ROLLBACK closes the lot.

ROLLBACK
ROLLBACK;
Result1 row · 1 column
status
Statement executed successfully.
And the transaction
SELECT CURRENT_TRANSACTION() AS THE_TRANSACTION_ID;
Result1 row · 1 column
THE_TRANSACTION_ID
NULL

NULL. So do not count your BEGINs and try to match them with COMMITs. There is only ever one transaction.

One last thing: let's turn AUTOCOMMIT off

We read the parameter at the top of the post. Now let's set it the other way and see what changes.

ALTER SESSION
ALTER SESSION SET AUTOCOMMIT = FALSE;
Result1 row · 1 column
status
Statement executed successfully.
Read it back
SELECT "key" AS THE_PARAMETER, "value" AS THE_VALUE, "default" AS THE_DEFAULT
FROM TABLE(RESULT_SCAN(LAST_QUERY_ID()));
Result1 row · 3 columns
THE_PARAMETERTHE_VALUETHE_DEFAULT
AUTOCOMMITfalsetrue

false, with the default still true.

Now an insert, with no BEGIN anywhere.

INSERT
INSERT INTO ACCOUNTS_T121 (ACCOUNT_ID, OWNER, BALANCE)
VALUES (9, 'eve', 1.00);
Result1 row · 1 column
number of rows inserted
1
And the transaction
SELECT CURRENT_TRANSACTION() AS THE_TRANSACTION_ID;
Result1 row · 1 column
THE_TRANSACTION_ID
1790732224625000000

One row inserted, and there is an id. The insert opened a transaction all by itself, which is exactly what the parameter's own description said it would do.

So the row is not committed. Let's roll it back and look.

ROLLBACK
ROLLBACK;
Result1 row · 1 column
status
Statement executed successfully.
And the row
SELECT COUNT(*) AS EVE_ROWS FROM ACCOUNTS_T121 WHERE OWNER = 'eve';
Result1 row · 1 column
EVE_ROWS
0

Zero. It was never really there.

Then the parameter goes back where we found it, because leaving a session parameter changed behind you is how you confuse the next person reading the same worksheet.

ALTER SESSION
ALTER SESSION SET AUTOCOMMIT = TRUE;
Result1 row · 1 column
status
Statement executed successfully.
Read it back
SELECT "key" AS THE_PARAMETER, "value" AS THE_VALUE, "default" AS THE_DEFAULT
FROM TABLE(RESULT_SCAN(LAST_QUERY_ID()));
Result1 row · 3 columns
THE_PARAMETERTHE_VALUETHE_DEFAULT
AUTOCOMMITtruetrue
And nothing is open
SELECT CURRENT_TRANSACTION() AS THE_TRANSACTION_ID;
Result1 row · 1 column
THE_TRANSACTION_ID
NULL

Back to true, and no transaction left open.

Cleanup
-- Put the schema back the way we found it.
DROP TABLE IF EXISTS ACCOUNTS_T121;
DROP TABLE IF EXISTS AUDIT_T121;
The last check
SELECT CURRENT_DATABASE()                 AS THE_DATABASE,
       CURRENT_SCHEMA()                   AS THE_SCHEMA,
       CURRENT_TRANSACTION()              AS ANY_TRANSACTION_STILL_OPEN,
       (SELECT COUNT(*) FROM INFORMATION_SCHEMA.TABLES
        WHERE RIGHT(TABLE_NAME, 5) = '_T121') AS PROBE_TABLES_LEFT,
       (SELECT COUNT(*) FROM CUSTOMERS)   AS DEMO_DB_IS_READABLE;
Result1 row · 5 columns
THE_DATABASETHE_SCHEMAANY_TRANSACTION_STILL_OPENPROBE_TABLES_LEFTDEMO_DB_IS_READABLE
DEMO_DBPUBLICNULL010

No transaction still open, no probe tables left, and the rest of the database still readable. That is the right last query for a file like this one.

Key points

  • AUTOCOMMIT is true by default, so every statement is already its own transaction. BEGIN is how you say not this time.
  • CURRENT_TRANSACTION() is the evidence column: an id inside a transaction, a real NULL outside one. Read it and you never have to guess.
  • ROLLBACK put the balances back and COMMIT kept them, and both can be proved with the numbers rather than described.
  • A DDL statement commits the transaction you had open. The transaction id was there before the CREATE TABLE and NULL after it.
  • The ROLLBACK that follows reports success and undoes nothing, because a ROLLBACK with nothing open is quietly accepted.
  • So create your tables before the transaction or after it, never in the middle of one.
  • A failed statement does not abort a Snowflake transaction. It stays open, it can still do work, and one ROLLBACK undoes all of it. That is the opposite of Postgres.
  • SHOW TRANSACTIONS lists what is open, with a state of running.
  • A second BEGIN returns the same id. It joins, it does not nest, so there is only ever one transaction to close.
  • With AUTOCOMMIT off, an INSERT with no BEGIN opens a transaction by itself, and a ROLLBACK removes the row.
  • Put a session parameter back the way you found it before you leave.
Next in this series

That is Level 10 finished — INSERT, UPDATE, DELETE, MERGE and transactions are all done. Episode 122 starts Level 11, loading and unloading: stages, file formats and COPY INTO.

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 account data is made up for teaching. The one refusal is a real captured error and is shown as it came back. The transaction ids and the session details in the grids are from that one run and will be different in yours. The _T121 tables are created and dropped by the script, and the AUTOCOMMIT parameter is set back before the end. Empty cells marked empty are empty strings and cells reading NULL are real nulls. Nothing here is timed and no performance claims are made anywhere in this series. Transaction behaviour follows the Snowflake transactions documentation.

No comments:

Post a Comment

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