Sub topic 4
Creating Tables with SQL and CTAS
This chapter assumes you can run SQL in a Databricks notebook, know basic data types, and have a Unity Catalog catalog and schema you can write to. The examples use main.sales. Replace it with your own catalog and schema.
The three-level name
Unity Catalog names a table with three parts: catalog.schema.table. In main.sales.orders, main is the catalog, sales is the schema, and orders is the table. If you leave out the catalog or schema, Databricks uses your session defaults. Full names avoid surprises.
Creating a table with an explicit schema
Use CREATE TABLE when you know the columns and types up front.
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;Each part does a specific job:
IF NOT EXISTSmakes the statement safe to re-run. If the table already exists, nothing happens and no error is raised.NOT NULLmakes Delta reject any write that puts a null inorder_id.DECIMAL(10,2)stores up to 10 digits, 2 of them after the decimal point. Use it for money instead ofDOUBLE, which can introduce rounding errors.USING DELTAnames the table format. On current Databricks runtimes, Delta is the default, so you can omit it. Keeping it makes the intent clear.
Because no LOCATION is given, this is a managed table. Unity Catalog chooses where the files are stored.
Creating a table from a query (CTAS)
CREATE TABLE AS SELECT, or CTAS, creates a table and fills it with the result of a query in one statement. You don't write the column list. The schema comes from the query.
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;The column names and types come from the SELECT list. That is why the aggregates have aliases (order_count, total_amount). Without aliases, the columns get generated names that are awkward to query.
CREATE vs. CREATE OR REPLACE
| Statement | If the table exists | Typical use |
|---|---|---|
| `CREATE TABLE` | Fails with an error | One-time setup where a duplicate is a mistake |
| `CREATE TABLE IF NOT EXISTS` | Does nothing | Idempotent setup scripts |
| `CREATE OR REPLACE TABLE` | Replaces the contents and schema | Rebuilding derived tables |
CREATE OR REPLACE keeps the table's history. The replacement is recorded as a new version, so you can still read the earlier data with time travel, covered in a later chapter. This differs from DROP TABLE followed by CREATE TABLE, which discards the history.
Common errors
- Table or view already exists. A plain
CREATE TABLEwas run twice. UseIF NOT EXISTSorCREATE OR REPLACE. - Schema or catalog not found. The three-level name points to something that does not exist, or you lack
USE SCHEMAandCREATE TABLEprivileges on it. - Constraints missing after CTAS. CTAS infers column names and types only. It does not copy
NOT NULLorCHECKconstraints from the source table. Declare those afterward, as the next chapters show. - Unexpected column names. An unaliased expression such as
COUNT(*)produces a name you did not choose. Always add an alias.
Exercise
You run CREATE OR REPLACE TABLE main.sales.orders_summary AS SELECT ... against an existing table. A teammate says the old data is gone for good. Are they right, and what is the difference from DROP TABLE followed by CREATE TABLE?
Show answer
They are not right. CREATE OR REPLACE writes the new contents as a new table version, so the previous version stays in the table history and can be read with time travel until it is vacuumed. DROP TABLE followed by CREATE TABLE creates a new table, so the earlier history is not carried over.
Exercise
Write a statement that creates a table main.sales.bigorders containing only rows from main.sales.orders where amount is at least 100. After it runs, does the new table have the NOT NULL rule on orderid?
Show answer
CREATE TABLE main.sales.big_orders AS SELECT * FROM main.sales.orders WHERE amount >= 100; The new table does not have the NOT NULL rule, because CTAS takes column names and types from the query and does not copy constraints. You would add the constraint afterward.