# CREATE TABLE
source: https://docs.chalk.ai/docs/chalksql/statements/create-table

## Create an empty table or save query results as a table in a connected SQL data source.

Use `CREATE TABLE` to define an empty table or `CREATE TABLE ... AS SELECT`
to save query results in a new table. Both forms support asynchronous execution
and return a `rows_written` column.

Target a writable [connected data source](/docs/chalksql/catalog/connected-data)
by its registered name. For example, `my_postgres.public.order_counts` names
the `order_counts` table in the `public` schema of `my_postgres`. Each write
requires the Chalk permission `chalk:datasource:write:my_postgres` for this
destination and database credentials with privileges for the operation.
Run each statement as a separate query.

### Create an empty table

Specify column names and types to create an empty, permanent table. Use
`IF NOT EXISTS` to keep an existing table with the same name.

```sql
CREATE TABLE IF NOT EXISTS my_postgres.public.order_counts (
    customer_id BIGINT PRIMARY KEY,
    order_count BIGINT NOT NULL
);
```

| rows_written |
| ------------ |
| 0            |

The destination determines which types, defaults, constraints, and layout
clauses you can use. For example, BigQuery supports `PARTITION BY` and
`CLUSTER BY`. Spanner requires a primary key.

### CREATE TABLE AS SELECT

Use `AS SELECT` to create and populate a table in one query. The result columns
supply the new table's names and types. Use aliases to name computed columns.

```sql
CREATE TABLE my_postgres.public.repeat_customers AS
SELECT customer_id, COUNT(*) AS order_count
FROM (VALUES (101), (101), (103), (103), (104)) AS orders(customer_id)
GROUP BY customer_id
HAVING COUNT(*) > 1;
```

| rows_written |
| ------------ |
| 2            |

You can also supply destination column names after the table name, as in
`CREATE TABLE my_postgres.public.repeat_customers (id, orders) AS SELECT ...`.
For Spanner, create a table with an explicit primary key and then [insert the query results](/docs/chalksql/statements/insert-into).





