Sub topic 4
Creating Tables with SQL and CTAS
This chapter covers creating Delta tables in Databricks with SQL: CREATE TABLE, CREATE TABLE AS SELECT (CTAS), and the options that change what each statement does. It assumes you know basic SQL (SELECT, INSERT, WHERE), can run a cell in a Databricks notebook on attached compute, and understand tables, schemas and data types. It also assumes you have read the earlier chapters on the transaction log and on managed and external tables.
Where a table lives: the three-level name
In Unity Catalog, every table has a three-level name: catalog.schema.table. The statements in this chapter use main.sales.orders, where main is the catalog, sales is the schema and orders is the table.
You need the following to create a table:
USE CATALOGon the catalog.USE SCHEMAandCREATE TABLEon the schema.
If you leave out the catalog or schema, Databricks uses the session defaults. You can set them like this:
USE CATALOG main;
USE SCHEMA sales;After that, orders resolves to main.sales.orders. Fully qualified names in shared notebooks and jobs are safer, because they do not depend on session state.
On current Databricks runtimes, Delta is the default table format. USING DELTA is therefore optional, but it makes the intent explicit and does no harm.
Creating a table with an explicit schema
The basic form lists columns and types:
CREATE TABLE IF NOT EXISTS main.sales.orders (
order_id BIGINT NOT NULL,
customer_id BIGINT,
order_ts TIMESTAMP,
amount DECIMAL(10,2),
status STRING
) USING DELTA;This statement does the following:
- Creates a managed table, because there is no
LOCATIONclause. Unity Catalog chooses the storage path and owns the data files. - Writes the first entry in the table's transaction log. The table starts empty, at version 0.
- Marks
order_idasNOT NULL. Any write that puts a null in that column fails. - Uses
DECIMAL(10,2)foramount. This gives exact arithmetic with up to 10 digits, 2 of them after the decimal point, which suits money better thanDOUBLE.
IF NOT EXISTS makes the statement safe to re-run. If the table already exists, nothing happens and no error is raised. It does not check that the existing table matches your column list, so a changed definition is silently ignored.
Useful clauses
You can add more clauses after the column list.
| Clause | Purpose |
|---|---|
| `COMMENT 'text'` | Describes the table. Column-level `COMMENT` is also supported. |
| `TBLPROPERTIES (key = value)` | Sets Delta and custom properties. |
| `LOCATION 'path'` | Makes the table external. See the chapter on table types. |
| `CLUSTER BY (col)` | Enables liquid clustering. |
| `PARTITIONED BY (col)` | Uses Hive-style partitioning. |
The following example combines several of them:
CREATE TABLE IF NOT EXISTS main.sales.customers (
customer_id BIGINT NOT NULL COMMENT 'Surrogate key',
email STRING,
created_at TIMESTAMP
)
USING DELTA
COMMENT 'One row per customer'
TBLPROPERTIES ('delta.enableChangeDataFeed' = 'true');Column and table comments appear in Catalog Explorer, so they are worth writing.
CREATE, CREATE OR REPLACE and IF NOT EXISTS
The three forms behave differently when the table already exists.
| Statement | Table exists | Table does not exist |
|---|---|---|
| `CREATE TABLE` | Fails with an error | Creates the table |
| `CREATE TABLE IF NOT EXISTS` | Does nothing | Creates the table |
| `CREATE OR REPLACE TABLE` | Replaces the definition and data | Creates the table |
CREATE OR REPLACE TABLE on a Delta table does not drop and recreate the table. It adds a new version to the existing log. Consequences:
- The table keeps its history, so you can still read earlier versions with time travel.
- The replacement is atomic. Readers see either the old version or the new one, never an empty table in between.
- Grants on the table are kept.
This is a major reason to prefer CREATE OR REPLACE TABLE over DROP TABLE followed by CREATE TABLE. The drop-and-create pair loses history and leaves a window where the table does not exist.
CREATE TABLE AS SELECT (CTAS)
CTAS creates a table and fills it from a query in one statement:
CREATE OR REPLACE TABLE main.sales.orders_summary AS
SELECT customer_id, COUNT(*) AS order_count, SUM(amount) AS total_amount
FROM main.sales.orders
GROUP BY customer_id;Key properties of CTAS:
- The schema comes from the query. Column names and types are those of the
SELECToutput.COUNT(*)becomesBIGINT, andSUMof aDECIMAL(10,2)becomes a wider decimal. - You cannot list column definitions. A CTAS statement does not accept a column list with types. To control the types, cast in the query:
CAST(amount AS DECIMAL(12,2)) AS amount. - Constraints are not carried over. A
NOT NULLcolumn in the source does not becomeNOT NULLin the new table. Add constraints afterwards, as described in the next chapter. - It is one atomic commit. If the query fails halfway, no table appears, so you never get a half-filled table.
- A snapshot, not a view. The result is a copy taken at that moment. Later changes to
ordersdo not reachorders_summary. If you need a live result, use a view or a materialized view.
Naming expressions
Every column in a CTAS output needs a valid name. Expressions without an alias get generated names such as count(1), which contain characters that Delta does not allow in column names by default. This is why the example above uses AS order_count and AS total_amount. Always alias computed columns.
Create an empty table with the same shape
To copy a structure without the rows, you can use a false predicate:
CREATE TABLE main.sales.orders_staging AS
SELECT * FROM main.sales.orders WHERE 1 = 0;Delta also supports CREATE TABLE ... LIKE, which copies the definition of an existing table without data:
CREATE TABLE main.sales.orders_copy LIKE main.sales.orders;Check which properties are copied in your runtime with DESCRIBE DETAIL on the new table.
Choosing between explicit DDL and CTAS
Both produce a Delta table, so the choice depends on what you need to control.
| Need | Better choice |
|---|---|
| Exact column types and `NOT NULL` from the start | `CREATE TABLE` with a column list, then `INSERT` |
| Column comments and constraints in one definition | `CREATE TABLE` with a column list |
| A derived table built from existing data | CTAS |
| Rebuild a table from scratch on each run | `CREATE OR REPLACE TABLE ... AS SELECT` |
| Empty table shaped like another | `CREATE TABLE ... LIKE` or CTAS with `WHERE 1 = 0` |
A common pattern is to define production tables explicitly, so the schema is reviewed and stable, and to use CTAS for derived and scratch tables.
The flow of the decision can be shown as a diagram.
Inserting data after creation
An explicit CREATE TABLE gives you an empty table. Fill it with INSERT:
INSERT INTO main.sales.orders VALUES
(1001, 1, TIMESTAMP'2026-12-01 09:30:00', 25.50, 'new'),
(1002, 2, TIMESTAMP'2026-12-01 10:05:00', 40.00, 'new');INSERT INTO matches columns by position. If the source has the same columns in a different order, the values land in the wrong columns, or the insert fails on a type mismatch. Two safer options are:
- List the target columns:
INSERT INTO main.sales.orders (order_id, customer_id, ...) SELECT .... - Use
INSERT INTO ... BY NAMEon runtimes that support it, which matches by column name.
Each INSERT is one atomic commit and creates one new table version. Inserting a single row at a time creates many small files, so batch your rows.
Inspecting what you created
After creating a table, check the result:
DESCRIBE EXTENDED main.sales.orders;
DESCRIBE DETAIL main.sales.orders;DESCRIBE EXTENDEDshows columns, types, comments, table type (MANAGEDorEXTERNAL), the storage location and table properties.DESCRIBE DETAILshows Delta-specific details, such as the number of files, the size in bytes, the clustering columns and the protocol versions.
SHOW CREATE TABLE main.sales.orders returns a statement you can use to recreate the definition, which is useful for migrating between environments.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| `TABLE_OR_VIEW_ALREADY_EXISTS` | Plain `CREATE TABLE` on an existing name | Use `IF NOT EXISTS` or `CREATE OR REPLACE` |
| `Found invalid character(s) among ' ,;{}()\n\t=' in the column names` | Unaliased expression in CTAS | Add `AS name` to every computed column |
| Permission error on create | Missing `CREATE TABLE` on the schema or `USE` on the catalog | Ask the owner to grant the privileges |
| Table definition did not change | `IF NOT EXISTS` skipped the statement | Use `ALTER TABLE` or `CREATE OR REPLACE` |
| CTAS table lost a `NOT NULL` | CTAS does not copy constraints | Add the constraint with `ALTER TABLE` |
Exercise
You run CREATE TABLE IF NOT EXISTS main.sales.orders (order_id BIGINT, status STRING) and the table already exists with five columns. What happens, and how would you change the table to have exactly these two columns?
Show answer
Nothing happens. IF NOT EXISTS skips the statement and does not compare definitions, so the table keeps its five columns. To change it, use CREATE OR REPLACE TABLE with the new definition, which adds a new version and replaces the data and schema, or use ALTER TABLE ... DROP COLUMN for the individual columns if the data should be kept.
Exercise
A colleague writes CREATE TABLE main.sales.daily AS SELECT order_date, SUM(amount) FROM main.sales.orders GROUP BY order_date and it fails with an invalid column name error. Why, and what is the fix? Also, will the new table keep a NOT NULL constraint that order_id had in the source?
Show answer
The expression SUM(amount) has no alias, so the generated name contains parentheses, which Delta does not accept in column names by default. Fix it with SUM(amount) AS total_amount. CTAS does not copy constraints from the source table, so any NOT NULL or CHECK constraints must be added afterwards with ALTER TABLE.