CREATE TABLE
statementpartialTables, views, streams, sequencesCreates a new table in the current/specified schema, replaces an existing table, or alters an existing table. A table can have multiple columns, with each column definition consisting of a name, data type, and optionally whether the column: - Requires a value (NOT NULL). - Has a default value. - Has any referential integrity constraints (primary key, foreign key, and so on). In addition, this command supports the following variants: - CREATE OR ALTER TABLE (creates a table if it doesn’t exist, or alters it according to the table definition) - DEFINE TABLE (declarative definition of a table’s target state inside a DCM project) - CREATE TABLE … AS SELECT (creates a populated table; also referred to as CTAS) - CREATE TABLE … USING TEMPLATE (creates a table with the column definitions derived from a set of staged files) - CREATE TABLE … LIKE (creates an empty copy of an existing table) - CREATE TABLE … CLONE (creates a clone of an existing table) - CREATE TABLE … FROM ARCHIVE OF (creates a table from archived data) - CREATE TABLE … FROM BACKUP SET (restores a table from a backup under a new name)
Syntax
supportedpartialnot supportednot scored
CREATE [ OR REPLACE ]
[ { [ { LOCAL | GLOBAL } ] TEMP | TEMPORARY | VOLATILE | TRANSIENT } ]
TABLE [ IF NOT EXISTS ] <table_name>
(
-- Column definition
<col_name> <col_type> [ [ GENERATED ALWAYS ] AS ( <expr> ) [ VIRTUAL ] ]
[ inlineConstraint ]
[ NOT NULL ]
[ COLLATE '<collation_specification>' ]
[
{
DEFAULT <expr>
| { AUTOINCREMENT | IDENTITY }
[
{
( <start_num> , <step_num> )
| START <num> INCREMENT <num>
}
]
[ { ORDER | NOORDER } ]
}
]
[ [ WITH ] MASKING POLICY <policy_name> [ USING ( <col_name> , <cond_col1> , ... ) ] ]
[ [ WITH ] PROJECTION POLICY <policy_name> ]
[ [ WITH ] TAG ( <tag_name> = '<tag_value>' [ , <tag_name> = '<tag_value>' , ... ] ) ]
[ COMMENT '<string_literal>' ]
-- Additional column definitions
[ , <col_name> <col_type> [ [ GENERATED ALWAYS ] AS ( <expr> ) [ VIRTUAL ] ] [ ... ] ]
-- Out-of-line constraints
[ , outoflineConstraint [ ... ] ]
)
[ CLUSTER BY { ( <expr> [ , <expr> , ... ] ) | AUTO } ]
[ ENABLE_SCHEMA_EVOLUTION = { TRUE | FALSE } ]
[ DATA_RETENTION_TIME_IN_DAYS = <integer> ]
[ MAX_DATA_EXTENSION_TIME_IN_DAYS = <integer> ]
[ CHANGE_TRACKING = { TRUE | FALSE } ]
[ DEFAULT_DDL_COLLATION = '<collation_specification>' ]
[ ICEBERG_DEFAULT_DDL_COLLATION = '<collation_specification>' ]
[ COPY GRANTS ]
[ ERROR_LOGGING = { TRUE | FALSE } ]
[ COPY TAGS ]
[ COPY = ( { COMMENTS | TAGS | GRANTS } [ , ... ] ) ]
[ COMMENT = '<string_literal>' ]
[ [ WITH ] ROW ACCESS POLICY <policy_name> ON ( <col_name> [ , <col_name> ... ] ) ]
[ [ WITH ] AGGREGATION POLICY <policy_name> [ ENTITY KEY ( <col_name> [ , <col_name> ... ] ) ] ]
[ [ WITH ] JOIN POLICY <policy_name> [ ALLOWED JOIN KEYS ( <col_name> [ , ... ] ) ] ]
[ [ WITH ] STORAGE LIFECYCLE POLICY <policy_name> ON ( <col_name> [ , <col_name> ... ] ) ]
[ [ WITH ] TAG ( <tag_name> = '<tag_value>' [ , <tag_name> = '<tag_value>' , ... ] ) ]
[ WITH CONTACT ( <purpose> = <contact_name> [ , <purpose> = <contact_name> ... ] ) ]
[ ROW_TIMESTAMP = { TRUE | FALSE } ]
AS ( expr ) defines the column as a virtual column. Snowflake computes the column’s values from the expression at query time. For ANSI SQL compatibility, you can also use the equivalent [ GENERATED ALWAYS ] AS ( expr ) [ VIRTUAL ] form. When you specify AS, the NOT NULL and DEFAULT clauses, and CHECK constraints, can’t be applied to the same column. For the full list of allowed expressions, data type rules, and restrictions, see Virtual Columns.
inlineConstraint ::=
[ CONSTRAINT <constraint_name> ]
{ UNIQUE
| PRIMARY KEY
| [ FOREIGN KEY ] REFERENCES <ref_table_name> [ ( <ref_col_name> ) ]
| CHECK ( <expr> )
}
[ <constraint_properties> ]
For additional inline constraint details, see CREATE | ALTER TABLE … CONSTRAINT.
outoflineConstraint ::=
[ CONSTRAINT <constraint_name> ]
{ UNIQUE [ ( <col_name> [ , <col_name> , ... ] ) ]
| PRIMARY KEY [ ( <col_name> [ , <col_name> , ... ] ) ]
| [ FOREIGN KEY ] [ ( <col_name> [ , <col_name> , ... ] ) ]
REFERENCES <ref_table_name> [ ( <ref_col_name> [ , <ref_col_name> , ... ] ) ]
| CHECK ( <expr> )
}
[ <constraint_properties> ]
[ COMMENT '<string_literal>' ]
Restored table (from a backup)
CREATE TABLE <name> FROM BACKUP SET <backup_set> IDENTIFIER '<backup_id>'
For more information, see CREATE OR ALTER TABLE usage notes and CREATE OR ALTER <object>.
CREATE OR ALTER
[ { [ { LOCAL | GLOBAL } ] TEMP | TEMPORARY | TRANSIENT } ]
TABLE <table_name> (
-- Column definition
<col_name> <col_type>
[ inlineConstraint ]
[ NOT NULL ]
[ COLLATE '<collation_specification>' ]
[
{
DEFAULT <expr>
| { AUTOINCREMENT | IDENTITY }
[
{
( <start_num> , <step_num> )
| START <num> INCREMENT <num>
}
]
[ { ORDER | NOORDER } ]
}
]
[ COMMENT '<string_literal>' ]
-- Additional column definitions
[ , <col_name> <col_type> [ ... ] ]
-- Out-of-line constraints
[ , outoflineConstraint [ ... ] ]
)
[ CLUSTER BY ( <expr> [ , <expr> , ... ] ) ]
[ ENABLE_SCHEMA_EVOLUTION = { TRUE | FALSE } ]
[ DATA_RETENTION_TIME_IN_DAYS = <integer> ]
[ MAX_DATA_EXTENSION_TIME_IN_DAYS = <integer> ]
[ CHANGE_TRACKING = { TRUE | FALSE } ]
[ DEFAULT_DDL_COLLATION = '<collation_specification>' ]
[ ICEBERG_DEFAULT_DDL_COLLATION = '<collation_specification>' ]
[ ERROR_LOGGING = { TRUE | FALSE } ]
[ COMMENT = '<string_literal>' ]
[ ROW_TIMESTAMP = { TRUE | FALSE } ]
Creates a new table populated with the data returned by a query
CREATE [ OR REPLACE ] TABLE <table_name> [ ( <col_name> [ <col_type> ] , <col_name> [ <col_type> ] , ... ) ]
[ CLUSTER BY ( <expr> [ , <expr> , ... ] ) ]
[ COPY GRANTS ]
[ COPY TAGS ]
[ COPY = ( { COMMENTS | TAGS | GRANTS } [ , ... ] ) ]
[ ... ]
AS <query>
A masking policy can be applied to a column in a CTAS statement. Specify the masking policy after the column data type. Similarly, a row access policy can be applied to the table. For example
CREATE TABLE <table_name> ( <col1> <data_type> [ WITH ] MASKING POLICY <policy_name> [ , ... ] )
...
[ WITH ] ROW ACCESS POLICY <policy_name> ON ( <col1> [ , ... ] )
[ ... ]
AS <query>
If the INFER_SCHEMA subquery specifies INFER_NESTED_TYPES => TRUE, columns that contain nested data are created as structured OBJECT, ARRAY, or MAP columns. For more information, see Create a table with structured columns from your files.
CREATE [ OR REPLACE ] TABLE <table_name>
[ COPY GRANTS ]
USING TEMPLATE <query>
[ ... ]
Creates a new table with the same column definitions as an existing table, but without copying data from the existing table. Column names, types, defaults, and constraints are copied to the new table
CREATE [ OR REPLACE ] TABLE <table_name> LIKE <source_table>
[ CLUSTER BY ( <expr> [ , <expr> , ... ] ) ]
[ COPY GRANTS ]
[ COPY TAGS ]
[ COPY = ( { COMMENTS | TAGS | GRANTS } [ , ... ] ) ]
[ ... ]
Creates a new table with the same column definitions and containing all the existing data from the source table, without actually copying the data. This variant can also be used to clone a table at a specific time/point in the past (using Time Travel)
CREATE [ OR REPLACE ]
[ {
[ { LOCAL | GLOBAL } ] TEMP [ READ ONLY ] |
TEMPORARY [ READ ONLY ] |
VOLATILE |
TRANSIENT
} ]
TABLE <name> CLONE <source_table>
[ { AT | BEFORE } ( { TIMESTAMP => <timestamp> | OFFSET => <time_difference> | STATEMENT => <id> } ) ]
[ COPY GRANTS ]
[ COPY TAGS ]
[ COPY = ( { COMMENTS | TAGS | GRANTS } [ , ... ] ) ]
[ ... ]
Creates a new table containing rows that were archived by a storage lifecycle policy. You can specify filter conditions to retrieve specific archived data.
CREATE [ TRANSIENT ] TABLE [ IF NOT EXISTS ] <name>
FROM ARCHIVE OF <source_table> [ [ AS ] <alias_name> ]
WHERE <expression>
Parameters
| Name | Required | Description |
|---|---|---|
name | required | Specifies the identifier (i.e. name) for the table; must be unique for the schema in which the table is created. In addition, the identifier must start with an alphabetic character and cannot contain spaces or special characters unless the entire identifier string is enclosed in double quotes (e.g. "My object"). Identifiers enclosed in double quotes are also case-sensitive. For more details, see Identifier requirements. |
col_name | required | Specifies the column identifier (i.e. name). All the requirements for table identifiers also apply to column identifiers. For more details, see Identifier requirements and Reserved & limited keywords. Note In addition to the standard reserved keywords, the following keywords cannot be used as column identifiers because they are reserved for ANSI-standard context functions: CURRENT_DATE CURRENT_ROLE CURRENT_TIME CURRENT_TIMESTAMP CURRENT_USER For the list of reserved keywords, see Reserved & limited keywords. |
col_type | required | Specifies the data type for the column. For details about the data types that can be specified for table columns, see SQL data types reference. |
query | required | Required for CTAS and USING TEMPLATE. For CTAS, specifies the SELECT statement that populates the table. This query must be specified last in the CTAS statement, regardless of the other parameters that you include. For CREATE TABLE … USING TEMPLATE, specifies the subquery that calls the INFER_SCHEMA function and formats the output as an array. Alternatively, USING TEMPLATE accepts the INFER_SCHEMA output as a string literal or variable. |
source_table | required | Required for LIKE, CLONE, and FROM ARCHIVE OF. For CREATE TABLE … LIKE, specifies the table from which properties and column definitions are copied. For CREATE TABLE … CLONE, specifies the table to use as the source for the clone. For CREATE TABLE … FROM ARCHIVE OF, see FROM ARCHIVE OF parameters. |
backup_set | Specifies the name of a backup set created for a specific table. You can use the SHOW BACKUP SETS command to locate the right backup set. | |
backup_id | Specifies the identifier of a specific backup within that backup set. You can use the SHOW BACKUPS IN BACKUP SET command to locate the right identifier within the backup set, based on the creation date and time for the backup. | |
source_table | Specifies the table whose rows have been archived by a storage lifecycle policy. This is the table from which archived data is retrieved. | |
[ AS ] alias_name | Specifies an optional alias name for the source table reference. Use this alias when referencing columns in the WHERE clause. Alias names must follow the rules for Object identifiers. | |
WHERE expression | Specifies a required condition that filters the archived rows to retrieve. The expression can reference columns from the source table (using the alias if specified). For more information about WHERE expressions, see WHERE. | |
{ [ { LOCAL | GLOBAL } ] TEMP [ READ ONLY] | TEMPORARY [ READ ONLY] | VOLATILE | TRANSIENT } | optional | Specifies that the table persists only for the duration of the session that you created it in. A temporary table and all its contents are dropped at the end of the session. For a temporary table that exists only for a single Snowflake Scripting stored procedure execution, use CREATE OR REPLACE PROCEDURE SCOPED TEMP TABLE inside the procedure body instead of CREATE TEMPORARY TABLE. See Procedure-scoped temporary tables (Snowflake Scripting). The synonyms and abbreviations for TEMPORARY (e.g. GLOBAL TEMPORARY) are provided for compatibility with other databases (e.g. to prevent errors when migrating CREATE TABLE statements). Tables created with any of these keywords appear and behave identically to a table created with the TEMPORARY keyword. Default: No value. If a table is not declared as TEMPORARY or TRANSIENT, the table is permanent. If you want to avoid unexpected conflicts, avoid naming temporary tables after tables that already exist in the schema. If you created a temporary table with the same name as another table in the schema, all queries and operations used on the table only affect the temporary table in the session, until you drop the temporary table. If you drop the table, you drop the temporary table, and not the table that already exists in the schema. For information about temporary or transient tables, and how they can affect storage and cost, refer to the following resources: Working with Temporary and Transient Tables Storage costs for Time Travel and Fail-safe READ ONLY Specifies that the table is read-only. READ ONLY is valid only for a temporary table that is being created with the CREATE TABLE … CLONE variant of the CREATE TABLE command. A read-only table does not allow DML operations and only allows the following subset of DDL operations: ALTER TABLE … { ALTER | MODIFY } COLUMN … { SET | UNSET } COMMENT ALTER TABLE … { ALTER | MODIFY } COLUMN … { SET | UNSET } MASKING POLICY ALTER TABLE … { ALTER | MODIFY } COLUMN … { SET | UNSET } TAG ALTER TABLE … RENAME COLUMN … TO ALTER TABLE … RENAME TO ALTER TABLE … { SET | UNSET } COMMENT ALTER TABLE … { SET | UNSET } TAG COMMENT DESCRIBE DROP SHOW UNDROP Read-only tables have a METADATA$ROW_POSITION column. This metadata column assigns a row number to each row in the table that is continuous and starts from 0. The row number assigned to each row remains unchanged until the read-only table is dropped. |
TRANSIENT | optional | Specifies that the table is transient. Like a permanent table, a transient table exists until explicitly dropped and is visible to any user with the appropriate privileges. However, transient tables have a lower level of data protection than permanent tables, meaning that data in a transient table might be lost in the event of a system failure. As such, transient tables should only be used for data that can be recreated externally to Snowflake. Default: No value. If a table is not declared as TRANSIENT or TEMPORARY, the table is permanent. Note Transient tables have some storage considerations. For more information about these and other considerations when deciding whether to create temporary or transient tables, see Working with Temporary and Transient Tables and Storage costs for Time Travel and Fail-safe. |
CONSTRAINT ... | optional | Defines an inline or out-of-line constraint for the specified column(s) in the table. For syntax details, see CREATE | ALTER TABLE … CONSTRAINT. For more information about constraints, see Constraints. |
COLLATE 'collation_specification' | optional | Specifies the collation to use for column operations such as string comparisons. This parameter applies only to text columns: VARCHAR, STRING, TEXT, and so on. For more information, see Collation specifications. |
DEFAULT ... or AUTOINCREMENT ... | optional | Specifies whether a default value is automatically inserted in the column if a value is not explicitly specified via an INSERT or CREATE TABLE AS SELECT statement: Note DEFAULT and AUTOINCREMENT are mutually exclusive; only one can be specified for a column.
|
MASKING POLICY = policy_name | optional | Specifies the masking policy to set on a column. This parameter is not supported by the CREATE OR ALTER variant syntax. |
PROJECTION POLICY policy_name | optional | Specifies the projection policy to set on a column. This parameter is not supported by the CREATE OR ALTER variant syntax. |
COMMENT 'string_literal' | optional | Specifies a comment for the column. (Note that comments can be specified at the column level or the table level. The syntax for each is slightly different.) |
USING ( col_name , cond_col_1 ... ) | optional | Specifies the arguments to pass into the conditional masking policy SQL expression. The first column in the list specifies the column for the policy conditions to mask or tokenize the data and must match the column to which the masking policy is set. The additional columns specify the columns to evaluate to determine whether to mask or tokenize the data in each row of the query result when a query is made on the first column. If the USING clause is omitted, Snowflake treats the conditional masking policy as a normal masking policy. |
CLUSTER BY ( expr [ , expr , ... ] ) | optional | Specifies one or more columns or column expressions in the table as the clustering key. For more details, see Clustering Keys & Clustered Tables. Default: No value (no clustering key is defined for the table) Important Clustering keys are not intended or recommended for all tables; they typically benefit very large (i.e. multi-terabyte) tables. Before you specify a clustering key for a table, you should understand micro-partitions. For more information, see Understanding Snowflake Table Structures. |
CLUSTER BY AUTO | optional | Enables automatic clustering key selection for the table. Snowflake chooses and applies the clustering key for you, and it can adjust the key over time. The table uses Optima Clustering. For more information, see Automatic clustering key selection. |
ENABLE_SCHEMA_EVOLUTION = { TRUE | FALSE } | optional | Enables or disables automatic changes to the table schema from data loaded into the table from source files, including: Added columns. By default, schema evolution is limited to a maximum of 100 added columns per load operation. To request more than 100 added columns per load operation, contact Snowflake Support. The NOT NULL constraint can be dropped from any number of columns missing in new data files. Setting it to TRUE enables automatic table schema evolution. The default FALSE disables automatic table schema evolution. Note Loading data from files evolves the table columns when all of the following are true: The COPY INTO <table> statement includes the MATCH_BY_COLUMN_NAME option. The role used to load the data has the EVOLVE SCHEMA or OWNERSHIP privilege on the table. For Snowpipe, the role that owns the pipe loads the data. Additionally, for schema evolution with CSV, when used with MATCH_BY_COLUMN_NAME and PARSE_HEADER, ERROR_ON_COLUMN_COUNT_MISMATCH must be set to false. To add nested columns as structured columns, also set the INFER_NESTED_TYPES copy option to TRUE. For more information, see Detect and evolve structured columns. |
DATA_RETENTION_TIME_IN_DAYS = integer | optional | Specifies the retention period for the table so that Time Travel actions (SELECT, CLONE, UNDROP) can be performed on historical data in the table. For more details, see Understanding & using Time Travel and Working with Temporary and Transient Tables. For a detailed description of this object-level parameter, as well as more information about object parameters, see Parameters. Values: Standard Edition: 0 or 1 Enterprise Edition: 0 to 90 for permanent tables 0 or 1 for temporary and transient tables Default: Standard Edition: 1 Enterprise Edition (or higher): 1 (unless a different default value was specified at the schema, database, or account level) Note A value of 0 effectively disables Time Travel for the table. |
MAX_DATA_EXTENSION_TIME_IN_DAYS = integer | optional | Object parameter that specifies the maximum number of days for which Snowflake can extend the data retention period for the table to prevent streams on the table from becoming stale. For a detailed description of this parameter, see MAX_DATA_EXTENSION_TIME_IN_DAYS. |
CHANGE_TRACKING = { TRUE | FALSE } | optional | Specifies whether to enable change tracking on the table. TRUE enables change tracking on the table. This setting adds a pair of hidden columns to the source table and begins storing change-tracking metadata in the columns. These columns consume a small amount of storage. The change-tracking metadata can be queried using the CHANGES clause for SELECT statements, or by creating and querying one or more streams on the table. FALSE does not enable change tracking on the table. Default: FALSE |
DEFAULT_DDL_COLLATION = 'collation_specification' | optional | Specifies a default collation specification for the columns in the table, including columns added to the table in the future. For more details about the parameter, see DEFAULT_DDL_COLLATION. |
ICEBERG_DEFAULT_DDL_COLLATION = 'collation_specification' | optional | Specifies a default collation specification for new string columns on Snowflake-managed Iceberg tables. For more information about the parameter, see ICEBERG_DEFAULT_DDL_COLLATION. |
COPY GRANTS | optional | Specifies to retain the access privileges from the original table when a new table is created using any of the following CREATE TABLE variants: CREATE OR REPLACE TABLE CREATE TABLE … LIKE CREATE TABLE … CLONE The parameter copies all privileges, except OWNERSHIP, from the existing table to the new table. The new table does not inherit any future grants defined for the object type in the schema. By default, the role that executes the CREATE TABLE statement owns the new table. If the parameter is not included in the CREATE TABLE statement, then the new table does not inherit any explicit access privileges granted on the original table, but does inherit any future grants defined for the object type in the schema. Note: With data sharing: If the existing table was shared to another account, the replacement table is also shared. If the existing table was shared with your account as a data consumer, and access was further granted to other roles in the account (using GRANT IMPORTED PRIVILEGES on the parent database), access is also granted to the replacement table. The SHOW GRANTS output for the replacement table lists the grantee for the copied privileges as the role that executed the CREATE TABLE statement, with the current timestamp when the statement was executed. The operation to copy grants occurs atomically in the CREATE TABLE command (i.e. within the same transaction). This parameter is not supported by the CREATE OR ALTER variant syntax. You can also copy grants with the COPY = ( GRANTS ) parameter. |
ERROR_LOGGING = { TRUE | FALSE } | optional | Specifies whether to turn on error logging for the table. When error logging is turned on, DML statements and supported data loading methods record errors in the table’s error table. TRUE turns on error logging for the table. An INSERT, UPDATE, or MERGE statement on the table that encounters a supported error no longer fails. Instead, it writes the other rows and records the error. For COPY INTO and Snowpipe, the ON_ERROR copy option still determines how a load handles errors and which errors are recorded. To set this property for an existing table, use a role that owns the table. FALSE turns off error logging for the table. If the table has an error table, turning off error logging drops the error table and the errors in it. The error table stores the source data of each error. Before you turn on error logging for a table that stores sensitive data, review which roles can query the error table, as described in Access control requirements for error tables. For more information, see Introduction to error logging. For DML statements, see Error logging for DML statements. For the errors that error logging records when you load files with COPY INTO or Snowpipe, see Error logging for COPY INTO and Snowpipe. Note If the OPT_OUT_ERROR_LOGGING parameter is set to TRUE for a session, DML statements, CREATE TABLE ... AS SELECT statements, and COPY INTO statements in the session don’t record errors, regardless of whether error logging is turned on for specific tables. For Snowpipe, only the value that’s set for the account applies. For more information, see Prevent or limit error logging. |
COPY TAGS | optional | Applies tags when you use any of these CREATE TABLE forms: CREATE OR REPLACE TABLE CREATE OR REPLACE TABLE … LIKE CREATE OR REPLACE TABLE … CLONE If the statement uses CREATE OR REPLACE TABLE … COPY TAGS without LIKE, CLONE, or a WITH TAG clause, tags from the replaced table and its columns are retained on the new table. If the statement uses LIKE, CLONE, or WITH TAG together with COPY TAGS, Snowflake combines tags from the applicable sources. If both sources set the same tag, the value from the replaced table (carried over by COPY TAGS) takes precedence. For more information, including the effect when you alter columns in the CREATE OR REPLACE statement, see the usage notes for COPY TAGS. You can also retain tags with the COPY = ( TAGS ) parameter. |
COPY = ( { COMMENTS | TAGS | GRANTS } [ , ... ] ) | optional | Names the kinds of metadata to carry over from the table being replaced onto the new table. Specify one or more kinds, separated by commas. The parentheses are required. Kind Carried over COMMENTS The table comment and the column comments of the replaced table. TAGS The tags of the replaced table and its columns. Equivalent to COPY TAGS. GRANTS The access privileges on the replaced table, except OWNERSHIP. Equivalent to COPY GRANTS.ExpandShow lessSee more COMMENTS and TAGS require OR REPLACE. GRANTS follows the same rules as COPY GRANTS: it requires OR REPLACE, LIKE, or CLONE. The parameter is accepted in the CREATE OR REPLACE TABLE, CTAS, LIKE, and CLONE forms. A column comment is carried over only when the new table defines a column with the same name and the same data type. Column order doesn’t matter. A column that is added, dropped, renamed, or retyped isn’t matched, so it doesn’t receive a comment. The table comment is carried over independently of whether any column matches. When the replaced table has a comment, that comment takes precedence over a comment the statement itself produces, whether the statement specifies an inline COMMENT or inherits one from a CLONE or LIKE source. An empty string counts as a comment. When the replaced table has no comment, or a matching column has none, the comment produced by the statement is kept. You can combine the COPY = ( ... ) parameter with the COPY GRANTS and COPY TAGS parameters in the same statement. Specifying the same kind both ways has no additional effect. For more information, see the usage notes for COPY = ( … ). |
COMMENT = 'string_literal' | optional | Specifies a comment for the table. Default: No value (Note that comments can be specified at the column level, constraint level, or table level. The syntax for each is slightly different.) |
ROW ACCESS POLICY policy_name ON ( col_name [ , col_name ... ] ) | optional | Specifies the row access policy to set on a table. This parameter is not supported by the CREATE OR ALTER variant syntax. |
AGGREGATION POLICY policy_name [ ENTITY KEY ( col_name [ , col_name ... ] ) ] | optional | Specifies an aggregation policy to set on a table. You can apply one or more aggregation policies on a table. Use the optional ENTITY KEY parameter to define which columns uniquely identify an entity within the table. For more information, see Implementing entity-level privacy with aggregation policies. You can specify one or more entity keys for an aggregation policy. This parameter is not supported by the CREATE OR ALTER variant syntax. |
JOIN POLICY policy_name [ ALLOWED JOIN KEYS ( col_name [ , ... ] ) ] | optional | Specifies the join policy to set on a table. Use the optional ALLOWED JOIN KEYS parameter to define which columns are allowed to be used as joining columns when this policy is in effect. For more information, see Join policies. This parameter is not supported by the CREATE OR ALTER variant syntax. |
STORAGE LIFECYCLE POLICY policy_name ON ( col_name [ , col_name ... ] ) | optional | Specifies a storage lifecycle policy to attach to the table. The columns specified in the ON clause must match the argument count and data types defined in the policy function signature. Snowflake uses these columns to evaluate the policy expression and determine which rows to archive or expire. Important If you attach an archival storage policy to a table, the table is permanently assigned to the specified archive tier for its lifetime. You can’t change the archive tier by applying a new policy. For example, you can’t specify a policy created with a COOL archive tier in ALTER TABLE…DROP STORAGE LIFECYCLE POLICY and then subsequently alter the table to add a policy created with a COLD archive tier. To alter the archive tier for a table, contact Snowflake Support to request deletion of the currently archived data. For additional considerations, see Archival storage policies. For more information about creating and managing storage lifecycle policies, see Create and manage storage lifecycle policies. This parameter is not supported by the CREATE OR ALTER variant syntax. |
ROW_TIMESTAMP = { TRUE | FALSE } | optional | Specifies whether to enable row timestamps on the table. You must use a role with the OWNERSHIP privilege. For more information, see Use row timestamps to measure latency in your pipelines. |
TAG ( tag_name = 'tag_value' [ , tag_name = 'tag_value' , ... ] ) | optional | Specifies the tag name and the tag string value. The tag value is always a string, and the maximum number of characters for the tag value is 256. For information about specifying tags in a statement, see Tag quotas. This parameter is not supported by the CREATE OR ALTER variant syntax. |
WITH CONTACT ( purpose = contact [ , purpose = contact ...] ) | optional | Associate the new object with one or more contacts. Specify the WITH CONTACT clause after all other clauses except the AS clause (if that clause is supported by this command). |
Usage notes
- A schema cannot contain tables and/or views with the same name. When creating a table: If a view with the same name already exists in the schema, an error is returned and the table is not created.
- If a table with the same name already exists in the schema, an error is returned and the table is not created, unless the optional OR REPLACE keyword is included in the command. Important Using OR REPLACE is the equivalent of using DROP TABLE on the existing table and then creating a new table with the same name; however, the dropped table is not permanently removed from the system. Instead, it is retained in Time Travel. This is important to note because dropped tables in Time Travel can be recovered, but they also contribute to data storage for your account. For more information, see Storage costs for Time Travel and Fail-safe. CREATE OR REPLACE <object> statements are atomic. That is, when an object is replaced, the old object is deleted and the new object is created in a single transaction. This means that any queries concurrent with the CREATE OR REPLACE TABLE operation use either the old or new table version. Recreating or swapping a table drops its change data. Any stream on the table becomes stale. In addition, any stream on a view that has this table as an underlying table, becomes stale. A stale stream is unreadable.
- The definition for a table is limited to 1 MB.
- The OR REPLACE and IF NOT EXISTS clauses are mutually exclusive. They can’t both be used in the same statement.
- Similar to reserved keywords, ANSI-reserved function names (CURRENT_DATE, CURRENT_TIMESTAMP, etc.) cannot be used as column names.
- CREATE OR ALTER TABLE: For more information, see CREATE OR ALTER TABLE usage notes.
- CREATE TABLE … CLONE: If the source table has clustering keys, then the new table has clustering keys. By default, Automatic Clustering is suspended for the new table – even if Automatic Clustering was not suspended for the source table.
- CREATE TABLE … FROM ARCHIVE OF: Using this command requires the OWNERSHIP privilege on the source table.
- Specifying column definitions, policies, tags, or other constraints isn’t supported. Snowflake automatically retrieves the table schema, policies, tags, and constraints from the source table. For details about how schema changes (column add or drop) on the source table affect restore, see Schema evolution.
- The WHERE clause is required. Reading archived data is expensive and should be performed infrequently. Filtering results using the WHERE clause helps you minimize costs by ensuring that Snowflake reads only the data that you require from archival storage.
- To estimate the number of files that Snowflake will retrieve from archive storage, run the EXPLAIN command before this operation. The output includes a createTableFromArchiveData operation and displays ARCHIVE OF table in the objects column for the TableScan operation. For more information, see Estimate retrieval costs with EXPLAIN.
- To see a history of data retrieval from archive storage, use the ARCHIVE_STORAGE_DATA_RETRIEVAL_USAGE_HISTORY view.
- When retrieving data from archive using CREATE TABLE … FROM ARCHIVE OF, if the source table inherits a tag-based masking policy from its parent schema or database, the target table must be created within the same schema or database from which the masking policy is inherited. Attempting to create the target table outside that boundary results in an error.
- To retrieve data from the COLD tier of archive storage, Snowflake must first restore the files from external cloud storage. This process can take up to 48 hours. To support this process, set the following parameters appropriately: STATEMENT_TIMEOUT_IN_SECONDS must be at least 48 hours.
- ABORT_DETACHED_QUERY must be FALSE.
- Run long retrievals as an asynchronous query from a driver instead of from Snowsight. For examples, see Performing an asynchronous query and Performing an asynchronous query.
- COLD storage tier restore operations support a maximum of 1 million files per restore operation.
- If you cancel a CREATE TABLE operation that retrieves data from archive storage, you might still incur retrieval costs.
- CREATE TABLE … CHANGE_TRACKING = TRUE: When change tracking is enabled, the table is locked for the duration of the operation. Locks can cause latency with some associated DDL/DML operations. For more information, refer to Resource locking.
- CREATE TABLE … LIKE: If the source table has clustering keys, then the new table has clustering keys. By default, Automatic Clustering is not suspended for the new table – even if Automatic Clustering was suspended for the source table.
- CREATE TABLE … AS SELECT (CTAS): If the aliases for the column names in the SELECT list are valid columns, then the column definitions are not required in the CTAS statement; if omitted, the column names and types are inferred from the underlying query: Copy code CREATE TABLE <table_name> AS SELECT ... Alternatively, the names can be explicitly specified using the following syntax: Copy code CREATE TABLE <table_name> ( <col1_name> , <col2_name> , ... ) AS SELECT ... The number of column names specified must match the number of SELECT list items in the query; the types of the columns are inferred from the types produced by the query.
- When clustering keys are specified in a CTAS statement: Column definitions are required and must be explicitly specified in the statement.
- By default, Automatic Clustering is enabled for the new table even if Automatic Clustering is suspended for the source table.
- The data is clustered when the new table is created. A clustered table generates a query plan that includes a sort operation and takes longer to create than an equivalent table that is not clustered. For example, the second of these commands is likely to take longer than the first: Copy code CREATE TABLE ctas_large_table AS SELECT * FROM large_table; CREATE TABLE ctas_clustered_large_table CLUSTER BY (timestamp) AS SELECT * FROM large_table; Alternatively, you can create a table with rows in sorted order by using an ORDER BY clause in the CTAS query.
- If the statement sets ERROR_LOGGING = TRUE, a supported error in a row, such as a conversion error or a CHECK constraint violation, doesn’t cause the statement to fail. Instead, the statement creates the table with the other rows and records the error in the new table’s error table. For more information, see Error logging for DML statements.
- CREATE OR REPLACE … COPY TAGS You don’t need privileges on the tags to use COPY TAGS.
- You can use COPY TAGS with a CREATE OR REPLACE … CLONE statement, a CREATE OR REPLACE … LIKE statement, or a WITH TAG clause. Tags from both sources are combined. If both sources set the same tag, the value from the replaced table (carried over by COPY TAGS) takes precedence.
- If you rename a tagged column in the statement, the column in the new table will not retain the tag.
- If you change the data type of a tagged column — for example, changing NUMBER(8) to NUMBER(16) — the column in the new table will not retain the tag.
- If you swap column names in the statement, the tag stays with the column based on its name. For example, suppose only column a has a tag and you run the following command to swap the names of columns a and b: Copy code CREATE OR REPLACE TABLE dst1 COPY TAGS AS SELECT b AS a, a AS b FROM src1 Only column a is still tagged in the new table, although it contains the data from column b in the source table.
- CREATE OR REPLACE … COPY = ( … ) You don’t need any privileges beyond those required to run the CREATE OR REPLACE statement.
- The statement is atomic. If the metadata can’t be carried over, the whole statement fails and the previous table is left unchanged.
- Column matching follows the same name and data type rules as COPY TAGS: renaming or retyping a column means the column in the new table doesn’t receive the carried-over comment.
- A statement that specifies COMMENTS or TAGS without OR REPLACE fails, as does a statement that specifies GRANTS without OR REPLACE, LIKE, or CLONE. CREATE OR ALTER TABLE doesn’t support the parameter.
- Inside a transaction, any DDL statement (including CREATE TEMPORARY/TRANSIENT TABLE) commits the transaction before executing the DDL statement itself. The DDL statement then runs in its own transaction. The next statement after the DDL statement starts a new transaction. Therefore, you can’t create, use, and drop a temporary or transient table within a single transaction. If you want to use a temporary or transient table inside a transaction, then create the table before the transaction, and drop the table after the transaction.
- Recreating a table (using the optional OR REPLACE keyword) drops its history, which makes any stream on the table stale. A stale stream is unreadable.
- A single masking policy that uses conditional columns can be applied to multiple tables provided that the column structure of the table matches the columns specified in the policy.
- When creating a table with a masking policy on one or more table columns, or a row access policy added to the table, use the POLICY_CONTEXT function to simulate a query on the column(s) protected by a masking policy and the table protected by a row access policy.
- For creating a table with the WITH STORAGE LIFECYCLE POLICY clause: You must have the necessary privileges to apply the policy. For information about required privileges, see Storage lifecycle policy privileges.
- A table can have only one attached storage lifecycle policy.
- The number of columns must match the argument count in the policy function signature, and the column data must be compatible with the argument types.
- Associated policies aren’t affected if you rename table columns. Snowflake associates policies to tables by using the column IDs.
- In order to evaluate and apply storage lifecycle policy expressions, Snowflake internally and temporarily bypasses any governance policies on a table.
- Regarding metadata: Attention Customers should ensure that no personal data (other than for a User object), sensitive data, export-controlled data, or other regulated data is entered as metadata when using the Snowflake service. For more information, see Metadata fields in Snowflake.
Access control requirements
A role used to execute this operation must have the following privileges at a minimum: Privilege | Object | Notes CREATE TABLE | Schema | Note that creating a temporary table does not require the CREATE TABLE privilege. SELECT | Table, external table, view | Required on queried tables and/or views only when cloning a table or executing CTAS statements. APPLY | Masking policy, row access policy, tag, storage lifecycle policy | Required only when applying a masking policy, row access policy, object tags, storage lifecycle policy, or any combination of these governance features when creating tables. USAGE (external stage) or READ (internal stage) | Stage | Required to derive table column definitions from staged files using CREATE TABLE … USING TEMPLATE statements. OWNERSHIP | Table | Required to execute a CREATE OR ALTER TABLE statement for an existing table. OWNERSHIP is a special privilege on an object that is automatically granted to the role that created the object, but can also be transferred using the GRANT OWNERSHIP command to a different role by the owning role (or any role with the MANAGE GRANTS privilege). Note that in a managed access schema, only the schema owner (i.e. the role with the OWNERSHIP privilege on the schema) or a role with the MANAGE GRANTS privilege can grant or revoke privileges on objects in the schema, including future grants. Operating on an object in a schema requires at least one privilege on the parent database and at least one privilege on the parent schema. For instructions on creating a custom role with a specified set of privileges, see Creating custom roles. For general information about roles and privilege grants for performing SQL actions on securable objects, see Overview of Access Control.
CREATE OR ALTER TABLE usage notes
- Limitations Currently only supports permanent, temporary, transient, and dynamic tables. Read-only, external, Apache Iceberg™, and hybrid tables are not supported. For dynamic tables, see CREATE OR ALTER DYNAMIC TABLE. - All limitations of the ALTER TABLE command apply. - Currently does not support the following: CREATE TABLE … AS SELECT (CTAS) variant syntax. - CREATE TABLE … USING TEMPLATE variant syntax. - CREATE TABLE … LIKE variant syntax. - CREATE TABLE … CLONE variant syntax. - Virtual columns (AS ( <expr> ) column definitions). - Table parameters and properties The absence of a property or parameter that was previously set in the modified table definition results in unsetting it. - Unsetting an explicit parameter value results in setting it to the default parameter value. If the parameter is set on the schema or database that contain the table, the table inherits the parameter value set on the schema or database. - A CREATE OR ALTER TABLE statement doesn’t change the ERROR_LOGGING property of an existing table, whether or not the statement sets it. To turn error logging on or off for an existing table, use ALTER TABLE. - Data governance Setting or unsetting a tag or policy on a table or column using a CREATE OR ALTER TABLE statement is not supported. Existing policies or tags are not altered by a CREATE OR ALTER statement and remain unchanged. - Constraints Setting or unsetting an inline primary key changes the nullability of the column accordingly. This aligns with the behavior of the CREATE TABLE command, but is different from the behavior of the ALTER TABLE command. - Columns New columns can only be added to the end of the column list. - Columns cannot be renamed. If you attempt to rename a column, the column is dropped and a new column is added. - The default value for a column can only be modified to use a sequence. - The default sequence for a column (for example, SET DEFAULT seq_name.NEXTVAL) can only be changed if the column already has a sequence. - For more information about modifying columns, see ALTER TABLE … ALTER COLUMN. - Collation Collation specifications cannot be altered. - Setting the DEFAULT_DDL_COLLATION parameter in the CREATE OR ALTER TABLE command sets the default collation specification for existing columns, which ensures the CREATE OR ALTER TABLE command yields the same results as the CREATE TABLE command. Therefore, you can’t use the CREATE OR ALTER TABLE command to set the DEFAULT_DDL_COLLATION parameter on a table that has existing text columns. You can, however, make collations explicit for existing columns when changing the DEFAULT_DDL_COLLATION parameter for a table. For example, create a new table my_table and set the default collation specification for the table to ‘fr’: Copy code CREATE OR ALTER TABLE my_table ( a INT PRIMARY KEY, b VARCHAR(20) ) DEFAULT_DDL_COLLATION = 'fr'; The collation specification for column b is ‘fr’ and cannot be changed. To change the default collation specification for table my_table, you must explicitly set the collation for text column b in the CREATE OR ALTER statement: Copy code CREATE OR ALTER TABLE my_table ( a INT PRIMARY KEY, b VARCHAR(200) COLLATE 'fr' ) DEFAULT_DDL_COLLATION = 'de'; - Atomicity The CREATE OR ALTER TABLE command does not guarantee atomicity. In the very rare case that a CREATE OR ALTER TABLE statement for an extremely wide table fails during execution, it is possible that a subset of changes might have been applied to the table. If there is a possibility of partial changes, the error message, in most cases, includes the following text: CREATE OR ALTER execution failed. Partial updates may have been applied. For example, if the statement is attempting to drop column A and add a new column B to a table, and the statement is aborted, it is possible that column A was dropped but column B was not added. Note If changes are partially applied, the resulting table is still in a valid state, and you can use additional ALTER TABLE statements to complete the original set of changes. To recover from partial updates, Snowflake recommends the following recovery mechanisms: Fix forward Re-execute the CREATE OR ALTER TABLE statement. If the statement succeeds on the second attempt, the target state is achieved. - Investigate the error message. If possible, fix the error and re-execute the CREATE OR ALTER TABLE statement. - Roll back If it is not possible to fix forward, Snowflake recommends manually rolling back partial changes: Investigate the state of the table using the DESCRIBE TABLE and SHOW TABLES commands. Determine which partial changes were applied, if any. - If any partial changes were applied, execute the appropriate ALTER TABLE statements to transform the table back to its original state. Note In some cases, you might not be able to undo partial changes. For more information, see the supported and unsupported actions for modifying column properties in the ALTER TABLE … ALTER COLUMN topic. - If you need help recovering from a partial update, contact Snowflake Support.
Known gaps
- AUTO, STATEMENT are not exercised by any test