Snowflake SQL Tutorial 107 - CREATE OR ALTER TABLE Drops The Column You Leave Out

Snowflake SQL · Episode 107

In this post we are going to cover CREATE OR ALTER TABLE in Snowflake.

It is a third way of writing CREATE TABLE. A plain CREATE fails if the name is taken. CREATE OR REPLACE throws away whatever was there and builds a new empty table. CREATE OR ALTER keeps the data and moves the table towards the definition you wrote.

We will start by checking the statement exists at all, then re-declare one table over and over and watch what each change costs. The second half is the list of things it will not do, in Snowflake's own words, because that list is what makes it a different tool rather than a safer one.

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

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

Let's check the statement exists on this account

CREATE OR ALTER is newer than most of this course, so before anything else let's find out whether this account will take it. The smallest possible one: one table, one column.

Query
-- Does this account have CREATE OR ALTER at all?
USE DATABASE DEMO_DB;
USE SCHEMA PUBLIC;

CREATE OR ALTER TABLE PROBE_T107 (ID INT);
Query
CREATE OR ALTER TABLE PROBE_T107 (ID INT);
Result1 row · 1 column
status
Table PROBE_T107 successfully created.

Created. So the statement exists here and the rest of the post is worth running.

Query
SELECT TABLE_NAME, COLUMN_NAME, DATA_TYPE
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = 'PUBLIC' AND TABLE_NAME = 'PROBE_T107'
ORDER BY ORDINAL_POSITION;
Result1 row · 3 columns
TABLE_NAMECOLUMN_NAMEDATA_TYPE
PROBE_T107IDNUMBER

And it made an ordinary table with an ordinary column. Nothing special about the object it produces.

Query
DROP TABLE IF EXISTS PROBE_T107;
Result1 row · 1 column
status
PROBE_T107 successfully dropped.

Let's create some sample data

Now a table with something in it. Three columns, a NOT NULL on the SKU, a default on the price, and a comment on the table so we can watch what happens to that too.

Sample data
-- Sample data for this post.
-- A small table we are going to re-declare over and over again.
USE DATABASE DEMO_DB;
USE SCHEMA PUBLIC;

CREATE OR REPLACE TABLE PRODUCTS_T107 (
    SKU    VARCHAR(10) NOT NULL,
    NAME   VARCHAR(40),
    PRICE  NUMBER(8,2) DEFAULT 0.00
)
COMMENT = 'episode 107 probe - the table we keep re-declaring';

INSERT INTO PRODUCTS_T107 (SKU, NAME, PRICE)
SELECT 'A-1', 'Anvil',    19.99
UNION ALL SELECT 'B-2', 'Bellows',  34.50
UNION ALL SELECT 'C-3', 'Crucible', 88.00;
Query
SELECT SKU, NAME, PRICE FROM PRODUCTS_T107 ORDER BY SKU;
Result3 rows · 3 columns
SKUNAMEPRICE
A-1Anvil19.99
B-2Bellows34.50
C-3Crucible88.00

Three products. This is the table we are going to re-declare for the rest of the post, and these three rows are how we will know what each way of writing it costs.

Let's start with a plain CREATE on a name that is taken

First the one everybody already knows. The same three columns, written again with no OR anything.

Query
CREATE TABLE PRODUCTS_T107 (
    SKU    VARCHAR(10) NOT NULL,
    NAME   VARCHAR(40),
    PRICE  NUMBER(8,2) DEFAULT 0.00
);
Query failed — Snowflake returned an error
002002 (42710): SQL compilation error:
Object 'PRODUCTS_T107' already exists.

002002, object already exists. Refused.

Query
SELECT COUNT(*) AS ROWS_PRESENT FROM PRODUCTS_T107;
Result1 row · 1 column
ROWS_PRESENT
3

And the rows are all still there. A refusal costs you nothing, which is worth saying out loud before we look at the alternative.

Now let's run the same definition with OR REPLACE

This is the one most deploy scripts use. Read the statement before you read the result: it is the same three columns, the same types, the same default. Nothing about the definition has changed.

Query
CREATE OR REPLACE TABLE PRODUCTS_T107 (
    SKU    VARCHAR(10) NOT NULL,
    NAME   VARCHAR(40),
    PRICE  NUMBER(8,2) DEFAULT 0.00
);
Result1 row · 1 column
status
Table PRODUCTS_T107 successfully created.

Succeeded. So what is in the table?

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

Zero rows. It dropped the table and built an identical empty one in its place.

And the comment?

Query
SELECT TABLE_NAME, COMMENT
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = 'PUBLIC' AND TABLE_NAME = 'PRODUCTS_T107';
Result1 row · 2 columns
TABLE_NAMECOMMENT
PRODUCTS_T107NULL

NULL, and that is a real NULL rather than an empty comment — the grid above marks those two things differently. The comment went with the table, because the table it was on does not exist any more.

Nothing changed and everything went

A statement that changed nothing cost everything that was in the table. That is the trap in a re-runnable deploy script: the file is correct, the statement succeeds, and the table is empty afterwards.

Now the same definition again, with OR ALTER

Let's put the three rows back and do it again, one word different.

Query
INSERT INTO PRODUCTS_T107 (SKU, NAME, PRICE) SELECT 'A-1', 'Anvil', 19.99
UNION ALL SELECT 'B-2', 'Bellows', 34.50
UNION ALL SELECT 'C-3', 'Crucible', 88.00;
Result1 row · 1 column
number of rows inserted
3
Query
SELECT COUNT(*) AS ROWS_PRESENT FROM PRODUCTS_T107;
Result1 row · 1 column
ROWS_PRESENT
3

Three rows, as before. Now the same definition with OR ALTER.

Query
CREATE OR ALTER TABLE PRODUCTS_T107 (
    SKU    VARCHAR(10) NOT NULL,
    NAME   VARCHAR(40),
    PRICE  NUMBER(8,2) DEFAULT 0.00
);
Result1 row · 1 column
status
Statement executed successfully.

Have a look at the status line. OR REPLACE said the table was successfully created. This one says the statement executed successfully, which is a different claim: it did not create anything.

Query
SELECT COUNT(*) AS ROWS_PRESENT FROM PRODUCTS_T107;
Result1 row · 1 column
ROWS_PRESENT
3
Query
SELECT SKU, NAME, PRICE FROM PRODUCTS_T107 ORDER BY SKU;
Result3 rows · 3 columns
SKUNAMEPRICE
A-1Anvil19.99
B-2Bellows34.50
C-3Crucible88.00

Three rows, same values. The table was already the shape we asked for, so there was nothing to do and nothing was done.

Let's put the two of them side by side

Two tables, built identically, with the same three rows in each. Then re-declared with one more column, one word apart.

Query
CREATE OR REPLACE TABLE REPLACE_SIDE_T107 (ID INT, LABEL VARCHAR(20));
Result1 row · 1 column
status
Table REPLACE_SIDE_T107 successfully created.
Query
CREATE OR REPLACE TABLE ALTER_SIDE_T107 (ID INT, LABEL VARCHAR(20));
Result1 row · 1 column
status
Table ALTER_SIDE_T107 successfully created.
Query
INSERT INTO REPLACE_SIDE_T107 (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
INSERT INTO ALTER_SIDE_T107 (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
CREATE OR REPLACE TABLE REPLACE_SIDE_T107 (ID INT, LABEL VARCHAR(20), EXTRA INT);
Result1 row · 1 column
status
Table REPLACE_SIDE_T107 successfully created.
Query
CREATE OR ALTER TABLE ALTER_SIDE_T107 (ID INT, LABEL VARCHAR(20), EXTRA INT);
Result1 row · 1 column
status
Statement executed successfully.

Now one row that says the whole difference.

Query
SELECT (SELECT COUNT(*) FROM REPLACE_SIDE_T107) AS ROWS_AFTER_OR_REPLACE,
       (SELECT COUNT(*) FROM ALTER_SIDE_T107)   AS ROWS_AFTER_OR_ALTER,
       (SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS
        WHERE TABLE_NAME = 'REPLACE_SIDE_T107') AS COLUMNS_AFTER_OR_REPLACE,
       (SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS
        WHERE TABLE_NAME = 'ALTER_SIDE_T107')   AS COLUMNS_AFTER_OR_ALTER;
Result1 row · 4 columns
ROWS_AFTER_OR_REPLACEROWS_AFTER_OR_ALTERCOLUMNS_AFTER_OR_REPLACECOLUMNS_AFTER_OR_ALTER
0333

Both tables ended up with the same number of columns. One of them kept its rows and the other did not. That is the sales pitch for CREATE OR ALTER, and it is true.

Now let's add a column by re-declaring the table

So what is it actually for? Changing a table by writing out what you want it to be, instead of writing the steps to get there.

Let's take our three columns and add a fourth: a boolean with a default of TRUE.

Query
CREATE OR ALTER TABLE PRODUCTS_T107 (
    SKU      VARCHAR(10) NOT NULL,
    NAME     VARCHAR(40),
    PRICE    NUMBER(8,2) DEFAULT 0.00,
    IN_STOCK BOOLEAN DEFAULT TRUE
);
Result1 row · 1 column
status
Statement executed successfully.
Query
SELECT SKU, NAME, PRICE, IN_STOCK FROM PRODUCTS_T107 ORDER BY SKU;
Result3 rows · 4 columns
SKUNAMEPRICEIN_STOCK
A-1Anvil19.99TRUE
B-2Bellows34.50TRUE
C-3Crucible88.00TRUE

The rows survived it, and look at the new column. Every one of them says TRUE. The rows already existed, and they were given the default.

Let's count that rather than read it.

Query
SELECT COUNT(*)                                   AS ROWS_TOTAL,
       COUNT(IN_STOCK)                            AS ROWS_WITH_A_VALUE,
       COUNT(*) - COUNT(IN_STOCK)                 AS ROWS_LEFT_NULL
FROM PRODUCTS_T107;
Result1 row · 3 columns
ROWS_TOTALROWS_WITH_A_VALUEROWS_LEFT_NULL
330

Every row has a value and none was left null. So one statement added the column and backfilled it.

Query
SELECT COLUMN_NAME, DATA_TYPE, IS_NULLABLE, COLUMN_DEFAULT
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = 'PUBLIC' AND TABLE_NAME = 'PRODUCTS_T107'
ORDER BY ORDINAL_POSITION;
Result4 rows · 4 columns
COLUMN_NAMEDATA_TYPEIS_NULLABLECOLUMN_DEFAULT
SKUTEXTNONULL
NAMETEXTYESNULL
PRICENUMBERYES0
IN_STOCKBOOLEANYESTRUE

And the catalog records it the way you would want: boolean, nullable, default TRUE. Have a look at the COLUMN_DEFAULT cells for SKU and NAME too. Those are real NULLs, meaning no default was declared, which is not the same thing as a default of null.

This is the whole appeal. Your script becomes the shape of the table, and you run the same file every time.

What happens when we leave a column out?

Now the question I could not predict, and it is the important one in this post.

Let's run the statement again with IN_STOCK simply absent from the text. Not dropped, not mentioned. I just did not write that line.

Query
CREATE OR ALTER TABLE PRODUCTS_T107 (
    SKU      VARCHAR(10) NOT NULL,
    NAME     VARCHAR(40),
    PRICE    NUMBER(8,2) DEFAULT 0.00
);
Result1 row · 1 column
status
Statement executed successfully.

Accepted, with the same quiet status line as before. So what does the table look like?

Query
SELECT COLUMN_NAME, DATA_TYPE
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = 'PUBLIC' AND TABLE_NAME = 'PRODUCTS_T107'
ORDER BY ORDINAL_POSITION;
Result3 rows · 2 columns
COLUMN_NAMEDATA_TYPE
SKUTEXT
NAMETEXT
PRICENUMBER
Query
SELECT COUNT(*) AS COLUMNS_NOW,
       SUM(IFF(COLUMN_NAME = 'IN_STOCK', 1, 0)) AS IN_STOCK_STILL_DECLARED
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = 'PUBLIC' AND TABLE_NAME = 'PRODUCTS_T107';
Result1 row · 2 columns
COLUMNS_NOWIN_STOCK_STILL_DECLARED
30

Three columns, and IN_STOCK is not one of them. It is not in the catalog at all.

A missing catalog row could still mean the data is sitting somewhere, so let's ask for the column and find out.

One note on the name in the next grid. When this demo first ran I did not know what the answer would be, so this query 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, on a table called PRODUCTS_T107B built and changed exactly the same way. That is the name you will see in this grid and in several more further down.

Setup for the follow-up run
-- The follow-up run, on a name of its own.
CREATE OR ALTER TABLE PRODUCTS_T107B (
    SKU    VARCHAR(10) NOT NULL,
    NAME   VARCHAR(40),
    PRICE  NUMBER(8,2) DEFAULT 0.00
);

INSERT INTO PRODUCTS_T107B (SKU, NAME, PRICE)
SELECT 'A-1', 'Anvil',    19.99
UNION ALL SELECT 'B-2', 'Bellows',  34.50
UNION ALL SELECT 'C-3', 'Crucible', 88.00;

-- Add the column, then re-declare without it, the same as above.
CREATE OR ALTER TABLE PRODUCTS_T107B (
    SKU      VARCHAR(10) NOT NULL,
    NAME     VARCHAR(40),
    PRICE    NUMBER(8,2) DEFAULT 0.00,
    IN_STOCK BOOLEAN DEFAULT TRUE
);

CREATE OR ALTER TABLE PRODUCTS_T107B (
    SKU    VARCHAR(10) NOT NULL,
    NAME   VARCHAR(40),
    PRICE  NUMBER(8,2) DEFAULT 0.00
);
Query
SELECT SKU, IN_STOCK FROM PRODUCTS_T107B ORDER BY SKU;
Query failed — Snowflake returned an error
000904 (42000): SQL compilation error: error line 1 at position 12
invalid identifier 'IN_STOCK'

000904, invalid identifier. The column and its data are gone.

Query
SELECT SKU, NAME, PRICE FROM PRODUCTS_T107 ORDER BY SKU;
Result3 rows · 3 columns
SKUNAMEPRICE
A-1Anvil19.99
B-2Bellows34.50
C-3Crucible88.00

The rows are all still here. It was only that column.

This is the sentence to take away

So CREATE OR ALTER is not “the safe CREATE OR REPLACE”. It converges the table to the text you gave it, in both directions.
Which means it is only safe if your file is complete. A column missing from your script is a column missing from your table, and nothing in the statement says the word DROP anywhere.

Will it add a NOT NULL while a NULL is sitting there?

Now the refusals, and each one tells you something different about how the statement works.

First, let's put a row in with no name, so the column holds a null.

Query
INSERT INTO PRODUCTS_T107 (SKU, NAME, PRICE) SELECT 'D-4', NULL, 5.00;
Result1 row · 1 column
number of rows inserted
1
Query
SELECT COUNT(*) AS ROWS_TOTAL, COUNT(NAME) AS ROWS_WITH_A_NAME
FROM PRODUCTS_T107;
Result1 row · 2 columns
ROWS_TOTALROWS_WITH_A_NAME
43

Four rows in the table and three of them have a name. Now let's declare that column NOT NULL.

Query
CREATE OR ALTER TABLE PRODUCTS_T107 (
    SKU      VARCHAR(10) NOT NULL,
    NAME     VARCHAR(40) NOT NULL,
    PRICE    NUMBER(8,2) DEFAULT 0.00
);
Query failed — Snowflake returned an error
001471 (42601): SQL compilation error:
Column 'NAME' contains null values. Not null constraint cannot be added.

Refused, and the message says exactly what it objects to: the column contains null values.

Query
SELECT COLUMN_NAME, IS_NULLABLE
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = 'PUBLIC' AND TABLE_NAME = 'PRODUCTS_T107'
ORDER BY ORDINAL_POSITION;
Result3 rows · 2 columns
COLUMN_NAMEIS_NULLABLE
SKUNO
NAMEYES
PRICEYES

And the column is still nullable, so the refusal cost us nothing.

Let's delete the row with the null and run the identical statement again.

Query
DELETE FROM PRODUCTS_T107 WHERE NAME IS NULL;
Result1 row · 1 column
number of rows deleted
1
Query
CREATE OR ALTER TABLE PRODUCTS_T107 (
    SKU      VARCHAR(10) NOT NULL,
    NAME     VARCHAR(40) NOT NULL,
    PRICE    NUMBER(8,2) DEFAULT 0.00
);
Result1 row · 1 column
status
Statement executed successfully.
Query
SELECT COLUMN_NAME, IS_NULLABLE
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = 'PUBLIC' AND TABLE_NAME = 'PRODUCTS_T107'
ORDER BY ORDINAL_POSITION;
Result3 rows · 2 columns
COLUMN_NAMEIS_NULLABLE
SKUNO
NAMENO
PRICEYES

Now it is NO. Same statement, different answer, because the refusal was about the data and not about the syntax.

Can it change a default?

Let's see what the price default is recorded as now.

Query
SELECT COLUMN_NAME, COLUMN_DEFAULT
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = 'PUBLIC' AND TABLE_NAME = 'PRODUCTS_T107'
ORDER BY ORDINAL_POSITION;
Result3 rows · 2 columns
COLUMN_NAMECOLUMN_DEFAULT
SKUNULL
NAMENULL
PRICE0

Zero, as declared. Now let's ask for a different one.

The first run of this demo asked for a narrower NAME and a new PRICE default in the same statement, which turns out to be a bad way to ask a question. Here is what came back.

Query
CREATE OR ALTER TABLE PRODUCTS_T107 (
    SKU      VARCHAR(10) NOT NULL,
    NAME     VARCHAR(4)  NOT NULL,
    PRICE    NUMBER(8,2) DEFAULT 9.99
);
Query failed — Snowflake returned an error
040050 (22000): SQL compilation error: cannot change column NAME from type VARCHAR(40) to VARCHAR(4) because reducing the byte-length of a varchar is not supported.

One message, about the varchar. The statement asked for two things the engine will not do and reported the first one it objected to, so that grid tells us nothing about defaults at all.

So the follow-up run asked for the default on its own, on PRODUCTS_T107B.

Query
SELECT COLUMN_NAME, COLUMN_DEFAULT
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = 'PUBLIC' AND TABLE_NAME = 'PRODUCTS_T107B'
ORDER BY ORDINAL_POSITION;
Result3 rows · 2 columns
COLUMN_NAMECOLUMN_DEFAULT
SKUNULL
NAMENULL
PRICE0
Query
CREATE OR ALTER TABLE PRODUCTS_T107B (
    SKU      VARCHAR(10) NOT NULL,
    NAME     VARCHAR(40),
    PRICE    NUMBER(8,2) DEFAULT 9.99
);
Query failed — Snowflake returned an error
000002 (0A000): Unsupported feature 'Alter Column Set Default'.

“Unsupported feature 'Alter Column Set Default'.” That is the whole message. Not a complaint about our data, and not a complaint about the syntax — the engine simply does not do this through this door. Episode 104 hit the same wall through ALTER COLUMN, and this refusal states it more plainly.

Query
SELECT COLUMN_NAME, COLUMN_DEFAULT
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = 'PUBLIC' AND TABLE_NAME = 'PRODUCTS_T107B'
  AND COLUMN_NAME = 'PRICE';
Result1 row · 2 columns
COLUMN_NAMECOLUMN_DEFAULT
PRICE0

The default did not move. And a row inserted afterwards takes the old one.

Query
INSERT INTO PRODUCTS_T107 (SKU, NAME) SELECT 'E-5', 'Ewer';
Result1 row · 1 column
number of rows inserted
1
Query
SELECT SKU, NAME, PRICE FROM PRODUCTS_T107 ORDER BY SKU;
Result4 rows · 3 columns
SKUNAMEPRICE
A-1Anvil19.99
B-2Bellows34.50
C-3Crucible88.00
E-5Ewer0.00

E-5 came in at the original default. So if you need a new default on an existing column, this statement is not the way to get it.

Can it narrow a VARCHAR? I was wrong about this one

This is the one I predicted would work. Let's look at the widths first.

Query
SELECT COLUMN_NAME, DATA_TYPE, CHARACTER_MAXIMUM_LENGTH
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = 'PUBLIC' AND TABLE_NAME = 'PRODUCTS_T107'
ORDER BY ORDINAL_POSITION;
Result3 rows · 3 columns
COLUMN_NAMEDATA_TYPECHARACTER_MAXIMUM_LENGTH
SKUTEXT10
NAMETEXT40
PRICENUMBERNULL

NAME is declared forty wide. And how long is the longest value actually in it?

Query
SELECT (SELECT MAX(LENGTH(NAME)) FROM PRODUCTS_T107B)   AS LONGEST_VALUE,
       (SELECT CHARACTER_MAXIMUM_LENGTH
        FROM INFORMATION_SCHEMA.COLUMNS
        WHERE TABLE_SCHEMA = 'PUBLIC' AND TABLE_NAME = 'PRODUCTS_T107B'
          AND COLUMN_NAME = 'NAME')                     AS THE_DECLARED_WIDTH,
       20                                               AS THE_WIDTH_I_WILL_ASK_FOR;
Result1 row · 3 columns
LONGEST_VALUETHE_DECLARED_WIDTHTHE_WIDTH_I_WILL_ASK_FOR
84020

Eight characters, in a column declared at forty, and we are about to ask for twenty. There is room to spare, so I expected this to be accepted.

Query
CREATE OR ALTER TABLE PRODUCTS_T107B (
    SKU      VARCHAR(10) NOT NULL,
    NAME     VARCHAR(20),
    PRICE    NUMBER(8,2) DEFAULT 0.00
);
Query failed — Snowflake returned an error
040050 (22000): SQL compilation error: cannot change column NAME from type VARCHAR(40) to VARCHAR(20) because reducing the byte-length of a varchar is not supported.

Refused. “reducing the byte-length of a varchar is not supported”.

So let's try it well below what the data needs, to see whether the message changes.

Query
CREATE OR ALTER TABLE PRODUCTS_T107B (
    SKU      VARCHAR(10) NOT NULL,
    NAME     VARCHAR(4),
    PRICE    NUMBER(8,2) DEFAULT 0.00
);
Query failed — Snowflake returned an error
040050 (22000): SQL compilation error: cannot change column NAME from type VARCHAR(40) to VARCHAR(4) because reducing the byte-length of a varchar is not supported.

The same message, for the same reason. Which tells us the rule is about the declaration and not about the data in the column. Snowflake is not measuring your values at all.

Query
SELECT COLUMN_NAME, CHARACTER_MAXIMUM_LENGTH
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = 'PUBLIC' AND TABLE_NAME = 'PRODUCTS_T107B'
  AND COLUMN_NAME = 'NAME';
Result1 row · 2 columns
COLUMN_NAMECHARACTER_MAXIMUM_LENGTH
NAME40
Result1 row · 2 columns
COLUMN_NAMECHARACTER_MAXIMUM_LENGTH
NAME40

The width never moved in either run. Now let's go the other way and widen it.

Query
CREATE OR ALTER TABLE PRODUCTS_T107B (
    SKU      VARCHAR(10) NOT NULL,
    NAME     VARCHAR(80),
    PRICE    NUMBER(8,2) DEFAULT 0.00
);
Result1 row · 1 column
status
Statement executed successfully.
Query
SELECT COLUMN_NAME, CHARACTER_MAXIMUM_LENGTH
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = 'PUBLIC' AND TABLE_NAME = 'PRODUCTS_T107B'
  AND COLUMN_NAME = 'NAME';
Result1 row · 2 columns
COLUMN_NAMECHARACTER_MAXIMUM_LENGTH
NAME80

Accepted immediately. So this is the same shape of rule we saw with clones in Episode 102: you can loosen a declaration, you cannot tighten it.

Can it reorder the columns?

One more, and it is a different kind of no. Let's write out the same three columns, with the same types, in a different order.

Query
SELECT ORDINAL_POSITION, COLUMN_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = 'PUBLIC' AND TABLE_NAME = 'PRODUCTS_T107B'
ORDER BY ORDINAL_POSITION;
Result3 rows · 2 columns
ORDINAL_POSITIONCOLUMN_NAME
1SKU
2NAME
3PRICE
Query
CREATE OR ALTER TABLE PRODUCTS_T107B (
    PRICE    NUMBER(8,2) DEFAULT 0.00,
    SKU      VARCHAR(10) NOT NULL,
    NAME     VARCHAR(80)
);
Query failed — Snowflake returned an error
002008 (55000): SQL compilation error:
Invalid operation column re-ordering is not possible in CREATE OR ALTER TABLE

002008, and the message names the statement: “column re-ordering is not possible in CREATE OR ALTER TABLE”. Nothing about our data, nothing about types, just a flat no to the operation.

Query
SELECT ORDINAL_POSITION, COLUMN_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = 'PUBLIC' AND TABLE_NAME = 'PRODUCTS_T107B'
ORDER BY ORDINAL_POSITION;
Result3 rows · 2 columns
ORDINAL_POSITIONCOLUMN_NAME
1SKU
2NAME
3PRICE
Result3 rows · 2 columns
ORDINAL_POSITIONCOLUMN_NAME
1SKU
2NAME
3PRICE

The order is as it was in both runs.

Query
SELECT * FROM PRODUCTS_T107 ORDER BY SKU;
Result4 rows · 3 columns
SKUNAMEPRICE
A-1Anvil19.99
B-2Bellows34.50
C-3Crucible88.00
E-5Ewer0.00

And that is the order a SELECT * gives you, which is the reason anybody wants to change it.

One question this post cannot answer

Here is a question I wanted to answer and cannot. Does CREATE OR ALTER keep a table comment that the new definition does not mention?

This is what the comment looks like at the end of the run.

Query
SELECT TABLE_NAME, COMMENT
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = 'PUBLIC' AND TABLE_NAME = 'PRODUCTS_T107';
Result1 row · 2 columns
TABLE_NAMECOMMENT
PRODUCTS_T107NULL
Why this grid does not answer it

That is a real NULL, and it is not evidence about CREATE OR ALTER. The OR REPLACE near the top of this post had already removed the comment, long before any of the OR ALTER statements ran. So there was no comment left for OR ALTER to keep or to drop.
To test it properly the comment has to be put back first, and nothing on this page does that. I would rather leave the question open than answer it from a grid that cannot settle it.

One last thing: what re-declaring can and cannot do, in one row

Let's finish with one row that holds the state of the follow-up table after everything above.

Query
SELECT (SELECT COUNT(*) FROM PRODUCTS_T107B)               AS ROWS_STILL_HERE,
       (SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS
        WHERE TABLE_NAME = 'PRODUCTS_T107B')               AS COLUMNS_NOW,
       (SELECT CHARACTER_MAXIMUM_LENGTH FROM INFORMATION_SCHEMA.COLUMNS
        WHERE TABLE_NAME = 'PRODUCTS_T107B' AND COLUMN_NAME = 'NAME')
                                                           AS NAME_WIDTH,
       (SELECT COLUMN_DEFAULT FROM INFORMATION_SCHEMA.COLUMNS
        WHERE TABLE_NAME = 'PRODUCTS_T107B' AND COLUMN_NAME = 'PRICE')
                                                           AS PRICE_DEFAULT;
Result1 row · 4 columns
ROWS_STILL_HERECOLUMNS_NOWNAME_WIDTHPRICE_DEFAULT
33800

The rows are still here, the column count is back to what the last accepted definition said, the name width is the widened one, and the price default never changed. Every one of those four numbers is the outcome of a section above.

  • It will add a column, and backfill it from the default.
  • It will drop a column you leave out, with its data.
  • It will add a NOT NULL, but only once the column has no nulls in it.
  • It will widen a VARCHAR. It will not narrow one, whatever is in the column.
  • It will not change a literal default, and it will not reorder your columns.

Which is why I would not describe it as a safer CREATE OR REPLACE. It is a different tool, and it trusts your file completely.

Finally, let's clean up after ourselves.

Cleanup
-- Put the schema back the way we found it.
DROP TABLE IF EXISTS PRODUCTS_T107;
DROP TABLE IF EXISTS REPLACE_SIDE_T107;
DROP TABLE IF EXISTS ALTER_SIDE_T107;
DROP TABLE IF EXISTS PRODUCTS_T107B;
Query
DROP TABLE IF EXISTS PRODUCTS_T107;
Result1 row · 1 column
status
PRODUCTS_T107 successfully dropped.
Result1 row · 1 column
status
REPLACE_SIDE_T107 successfully dropped.
Result1 row · 1 column
status
ALTER_SIDE_T107 successfully dropped.
Query
SELECT CURRENT_DATABASE()                 AS THE_DATABASE,
       CURRENT_SCHEMA()                   AS THE_SCHEMA,
       (SELECT COUNT(*) FROM INFORMATION_SCHEMA.TABLES
        WHERE RIGHT(TABLE_NAME, 5) = '_T107') 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

  • A plain CREATE on a taken name is refused with 002002 and the table is left completely alone.
  • CREATE OR REPLACE with an unchanged definition still empties the table, and takes the comment with it.
  • CREATE OR ALTER with the same definition keeps the rows and their values, and reports that a statement executed rather than that a table was created.
  • Adding a column by re-declaring works, and the rows that already existed are given the new column's default.
  • A column left out of the definition is dropped, with its data, and a later SELECT of it gets 000904, invalid identifier.
  • So it converges the table to your text. It is only safe if your file is complete.
  • It will not add a NOT NULL while the column holds a null. Clear the null and the identical statement is accepted.
  • It cannot change a literal default: Unsupported feature 'Alter Column Set Default'. A row inserted afterwards still takes the old one.
  • It will not narrow a VARCHAR, even to a width the data fits inside. The rule is about the declaration, not the data. Widening is accepted at once.
  • It will not reorder columns, and says so by name: column re-ordering is not possible in CREATE OR ALTER TABLE.
  • A statement that asks for two unsupported changes reports only one of them, so ask one question at a time.
Next in this series

Episode 108 — views. A view is not a table that updates itself, it is a query with a name. What that means for writing through one, for SELECT * inside one, and for what happens when the table underneath it goes away.

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. The episode ran twice and the post says where it switches: grids naming PRODUCTS_T107 are from the first run, and the isolated refusals on PRODUCTS_T107B are from a follow-up run that re-asked the four questions whose messages the first run lost. The setup for that follow-up run appears as plain code with no grid. One grid on this page cannot answer the question it is pointed at, 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 and no performance claims are made anywhere in this series. Behaviour follows the Snowflake CREATE TABLE documentation.

No comments:

Post a Comment

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