# CREATE TABLE AS SELECT Statement Syntax for Hive

A `CREATE TABLE AS SELECT` (CTAS) statement creates a new table from the result of a `SELECT` query and writes that result into it. Data engineers use it to save an aggregation or a filtered copy of a table as a table with a single HiveQL statement — for example, to keep an intermediate result of a workflow or to prepare the output table of a scheduled query. To create an empty table with a schema you define, use [CREATE TABLE](/products/customer-data-platform/data-workbench/queries/sql-reference/create_table). To remove a table, use [DROP TABLE](/products/customer-data-platform/data-workbench/queries/sql-reference/drop_table).

## Syntax

```sql
CREATE TABLE [IF NOT EXISTS] [<database_name>.]<table_name>
[COMMENT '<table_comment>']
[TBLPROPERTIES ('<key>' = '<value>', ...)]
AS <select_statement>
```

Where:

- <table_name> is the name of the table to create.
- <select_statement> is the `SELECT` statement that returns the data to write. A `WITH` clause (CTE) can also be used.
- `IF NOT EXISTS` makes the statement succeed without doing anything when a table with the same name already exists. See [IF NOT EXISTS Behavior](#if-not-exists-behavior).
- `COMMENT` sets an optional description for the table.
- `TBLPROPERTIES` sets optional table properties. See [Supported Table Properties](#supported-table-properties).


The column names and data types of the table come from the output of the `SELECT`, so you cannot specify a column definition list as you can with `CREATE TABLE`.

## Examples

Create a new table from selected columns of a table:

```sql
CREATE TABLE my_database.jp_users AS
SELECT user_id, country, score
FROM users
WHERE country = 'JP';
```

Use a `WITH` clause (CTE):

```sql
CREATE TABLE high_scores AS
WITH jp AS (
  SELECT * FROM users WHERE country = 'JP'
)
SELECT user_id, score
FROM jp
WHERE score >= 80;
```

Create a table only if it does not already exist:

```sql
CREATE TABLE IF NOT EXISTS daily_summary AS
SELECT country, COUNT(*) AS user_count
FROM users
GROUP BY country;
```

Set a table comment and a data retention period with `expire_days`. If the `SELECT` includes the `time` column, the time of the original records is kept as is:

```sql
CREATE TABLE recent_purchases
COMMENT 'Purchase events'
TBLPROPERTIES ('expire_days' = '30')
AS
SELECT time, user_id, event_type
FROM user_events
WHERE event_type = 'purchase';
```

Distribute data with User-Defined Partitioning (UDP):

```sql
CREATE TABLE user_events_udp
TBLPROPERTIES (
  'udp.bucket_count' = '16',
  'udp.bucketed_on' = 'user_id'
)
AS
SELECT user_id, event_type
FROM user_events;
```

## Behavior

### Table Creation and Data Writing

CTAS creates the destination table when the query starts to run. It then writes the result of the `SELECT`, and the data is committed when the query completes. While the query is running, the table exists but contains no data. When the query completes, the number of written records is shown in the job log.

`EXPLAIN CREATE TABLE ... AS SELECT ...` only shows the execution plan and does not create the table.

### Columns

The column names of the table are the column names in the output of the `SELECT`, including aliases set with `AS`. We recommend setting an alias with `AS` for the result of an expression. Without an alias, the column gets a name such as `_c0`.

A column name can contain only lower-case letters, digits, and underscores (`_`), cannot start with a digit, and can be up to 128 characters long. A name that does not follow these rules causes an error before the query runs.

### The time Column

Tables in Data Workbench have a `time` column that holds the time of each record.

- If the output of the `SELECT` has no `time` column, a `time` column is added automatically. Its value is the time the query ran.
- If the output of the `SELECT` has a `time` column, its value becomes the time of the record. The type of the `time` column must be `INT` or `BIGINT`. Any other type causes an error.


### Supported Data Types

The data types that the output can contain are listed below.

| Hive Type | CDP Column Type | Notes |
|  --- | --- | --- |
| `STRING` | `string` |  |
| `BIGINT` | `long` |  |
| `INT`, `INTEGER`, `SMALLINT`, `TINYINT` | `long` |  |
| `DOUBLE`, `FLOAT` | `double` |  |
| `ARRAY<type>` | `array` | The element type must also be one of the types above. |


If the output contains any other data type, the statement fails and the table is not created. For `BOOLEAN`, `DECIMAL`, `TIMESTAMP`, `DATE`, `VARCHAR`, and `CHAR`, the error is `Failed to convert the type of <column_name>`. For `MAP` and `STRUCT`, the error is `Column type: <type> not supported`. Use `CAST` to convert the column to a supported type, for example `CAST(is_active AS STRING)`.

```sql
CREATE TABLE flags AS
SELECT user_id, CAST(is_active AS STRING) AS is_active
FROM users;
```

### IF NOT EXISTS Behavior

If you specify `IF NOT EXISTS` and a table with the same name already exists, the query succeeds without running the `SELECT` and without writing any data. The existing table is not changed. Without `IF NOT EXISTS`, the statement fails with the error `Table already exists`, and the job is not run again automatically.

### Settings of the Source Table

A table created with CTAS does not inherit the comment, `expire_days`, or UDP of the source table. If you need these settings, specify them with `COMMENT` and `TBLPROPERTIES`.

To create a new table that takes over the settings of an existing table, use [CREATE TABLE ... LIKE](/products/customer-data-platform/data-workbench/queries/sql-reference/create_table) to create a table that copies the schema, `expire_days`, and UDP, and then write the data with `INSERT INTO ... SELECT`.

```sql
CREATE TABLE new_events LIKE user_events;
INSERT INTO new_events SELECT * FROM user_events;
```

### Permissions

You need permission to create tables in the destination database and permission to read the tables that the `SELECT` references. In the database access levels of the Console, the destination requires `Full access`. With `Query only` or `Import only`, you cannot create the table. Without permission, the statement fails with an authorization error and the table is not created.

## Supported Table Properties

Only the following properties are processed. All other properties are ignored. The same validation as for `CREATE TABLE` applies, and an invalid value causes an error before the query runs.

| Property | Type | Description |
|  --- | --- | --- |
| `comment` | String | A description of the table. This is equivalent to the table-level `COMMENT` clause. |
| `expire_days` | Integer | The number of days after which data is automatically deleted. Must be a positive integer. |
| `udp.bucket_count` | Integer | The number of buckets for User-Defined Partitioning. Must be a power of 2 between 4 and 4096. We recommend starting with 512. |
| `udp.bucketed_on` | String | A comma-separated list of columns to bucket on. Up to 3 columns, which must be in the output of the `SELECT`. Cannot include the `time` column. |


Note
`udp.bucket_count` and `udp.bucketed_on` must be specified together, or neither. For CTAS, the columns in `udp.bucketed_on` can only be of type `STRING`, `INT`, or `BIGINT`. For more details on User-Defined Partitioning, see the [User-Defined Partitioning (UDP)](/products/customer-data-platform/data-workbench/queries/sql-reference/udp) page.

## Failure Behavior

CTAS creates the table before it writes the data, so a table can remain if the query fails partway. The behavior depends on the kind of failure.

- **Validation error before execution** (for example, an unsupported clause, an invalid table property, an invalid column name, or an unsupported data type): The table is not created. The job is not run again automatically for this error. Fix the query and run it again.
- **Error during execution**: The created table is dropped automatically. If the failure is caused by a temporary problem, Treasure AI may run the job again from the beginning. The job log shows the message `dropped the partially-created table`.
- **Hive runs the query again within the same job**: After an error during execution, Hive can run the query again inside the same job. The second run stops with `Table already exists` (or, with `IF NOT EXISTS`, with a message saying that Hive executed the query again), and the created table is dropped. The job is not run again automatically. Check the error and run the job again manually.


### Leftover Tables

In rare cases, such as when the query process terminates abruptly or the table cannot be dropped, an empty or incomplete table can remain. If the table cannot be dropped, the error message names the table. Check the remaining table, drop it with [DROP TABLE](/products/customer-data-platform/data-workbench/queries/sql-reference/drop_table) if you do not need it, and then run the query again.

Warning
If you run a CTAS with `IF NOT EXISTS` again while such a table remains, the query succeeds without writing any data. A successful job does not always mean that data was written. Check the contents of the table, or drop the table first.

### Existing Table When a Job Is Run Again

If a job is run again from the beginning, for example after a temporary problem, and a CTAS with `IF NOT EXISTS` finds that the table already exists, the job fails instead of succeeding. The query cannot tell whether an earlier run created the table and stopped midway, or whether the table existed before, and it does not report an empty or incomplete table as a success. Check the contents of the table, drop it with [DROP TABLE](/products/customer-data-platform/data-workbench/queries/sql-reference/drop_table) if it is incomplete, and run the query again.

## Limitations

### Unsupported Clauses

The following clauses are not supported and are rejected with an error before the query runs:

- `TEMPORARY`
- `EXTERNAL`
- `TRANSACTIONAL`
- `MANAGED`
- `PARTITIONED BY`
- `ROW FORMAT`
- `STORED AS`
- `STORED BY`
- `LOCATION`
- `SKEWED BY`