Sub topic 1
Creating a table with CREATE TABLE
CREATE TABLE defines a table's structure: its name, its columns, and the type of value each column holds. This chapter covers the statement's syntax, how to run it safely, and the errors you are most likely to hit. Later chapters cover data types and constraints in detail, so the examples here stay minimal.
Prerequisites
This chapter assumes you can already:
- Read and write basic
SELECT,INSERT,UPDATE, andDELETEstatements. - Describe a table in terms of rows and columns.
- Recognize common data types such as integers, text, and dates.
The examples use standard SQL and run in PostgreSQL. Where MySQL, SQL Server, or SQLite differ, the text says so.
The shape of the statement
A table definition lists a name and then a comma-separated list of column definitions inside parentheses. Each column definition has at least a column name and a data type.
CREATE TABLE customers (
customer_id INTEGER,
email VARCHAR(255),
full_name VARCHAR(100),
created_at TIMESTAMP
);This statement creates an empty table with four columns. It stores no rows yet, and it enforces almost nothing. Any column can hold NULL, and nothing stops two rows from sharing the same customer_id. Constraints add those protections, and they are the subject of the following chapters.
Reading a column definition
Each column definition follows this pattern:
column_name data_type [column modifiers]The modifiers are things like NOT NULL or DEFAULT. They come after the data type. A few rules apply to the whole list:
- Commas separate items. There is no comma after the last item, and a trailing comma is a syntax error in most systems.
- Column names must be unique within the table.
- Column order is the order in which
SELECT *returns the columns. Most systems cannot reorder columns later without rebuilding the table, so put the key columns first. - A table needs at least one column.
Checking that the table works
After creating a table, insert a row and read it back. Name the columns in the INSERT so the statement does not depend on column order.
INSERT INTO customers (customer_id, email, full_name, created_at)
VALUES (1, '[email protected]', 'Ada Lovelace', CURRENT_TIMESTAMP);
SELECT customer_id, email, full_name
FROM customers;A column you leave out of the INSERT list receives its default value. With no DEFAULT clause, that value is NULL.
Naming tables and columns
Names are identifiers, and a few conventions prevent most trouble.
- Use lowercase letters, digits, and underscores, and start with a letter.
customer_idworks everywhere. - Pick one naming style, such as plural table names (
customers) and singular column names (email), and use it throughout. - Avoid reserved words. A table named
orderfails, becauseORDERis part ofORDER BY.
CREATE TABLE order (
order_id INTEGER
);
-- ERROR: syntax error at or near "order"You can force a reserved word to work by quoting it, with double quotes in standard SQL and PostgreSQL, backticks in MySQL, or square brackets in SQL Server. Every later query must then quote it the same way, so renaming the table to orders is the better fix.
Quoting also changes case handling. PostgreSQL folds unquoted names to lowercase, so Customers and customers are the same table. A quoted "Customers" is a different, case-sensitive name.
Schemas and qualified names
A schema is a named container for tables within a database. You can place a table in a schema by qualifying its name:
CREATE SCHEMA shop;
CREATE TABLE shop.products (
product_id INTEGER,
name VARCHAR(100)
);
SELECT product_id, name FROM shop.products;An unqualified name goes into the first schema on the session's search path. In PostgreSQL that is usually public. In MySQL, "schema" and "database" mean the same thing, and CREATE SCHEMA creates a database.
Creating a table only when it is missing
Running CREATE TABLE twice for the same name fails.
CREATE TABLE customers (customer_id INTEGER);
-- ERROR: relation "customers" already existsAdding IF NOT EXISTS turns the error into a skipped statement:
CREATE TABLE IF NOT EXISTS customers (
customer_id INTEGER,
email VARCHAR(255)
);PostgreSQL, MySQL, and SQLite accept this. SQL Server does not accept it in CREATE TABLE, so scripts there test for the table first, for example with IF OBJECT_ID('customers', 'U') IS NULL.
IF NOT EXISTS checks only the name. If a table called customers already exists with different columns, the statement does nothing and does not tell you the definitions differ. Your script then carries on against the wrong structure. Use it for setup scripts that must be safe to rerun. Do not use it as a way to change an existing table.
Removing and rebuilding
DROP TABLE deletes a table together with all its rows. It is permanent unless you are inside a transaction that you can roll back.
DROP TABLE IF EXISTS customers;During development you often drop and recreate a table. Two risks apply:
- A table that other tables reference through a foreign key cannot be dropped until those references are removed. PostgreSQL offers
DROP TABLE ... CASCADE, which removes the dependent constraints. Use it deliberately, because it changes other tables. - PostgreSQL and SQL Server can roll back DDL (the statements that define structure) inside a transaction. MySQL commits implicitly after each DDL statement, so a mistaken
DROP TABLEthere cannot be undone.
Creating a table from a query
CREATE TABLE ... AS builds a table from the result of a SELECT and fills it with the returned rows in one step.
CREATE TABLE customers_archive AS
SELECT customer_id, email, full_name
FROM customers
WHERE created_at < DATE '2025-01-01';The new table takes its column names and types from the query. It does not copy constraints, defaults, or indexes, so you must add those afterward. This form suits snapshots and scratch copies, and it is a poor choice for a table that should protect its own data. SQL Server uses SELECT ... INTO customers_archive FROM ... for the same job.
Temporary tables
A temporary table exists only for your session, and the system drops it automatically when the session ends. Other sessions cannot see it.
CREATE TEMPORARY TABLE recent_orders (
order_id INTEGER,
placed_at TIMESTAMP
);PostgreSQL, MySQL, and SQLite use CREATE TEMPORARY TABLE. SQL Server instead uses a name that starts with #, as in CREATE TABLE #recent_orders (...).
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| `syntax error at or near ...` | Reserved word as a name, a missing comma, or a trailing comma | Rename the item or fix the comma list |
| `relation "x" already exists` | The table is already there | Use `IF NOT EXISTS`, or drop the table first if you mean to rebuild it |
| `type "x" does not exist` | Misspelled or unsupported data type | Check the type name for your database system |
| `column "x" specified more than once` | Duplicate column name | Rename one of the columns |
| `permission denied for schema ...` | Your role lacks `CREATE` rights on the schema | Ask for the privilege or use another schema |
What comes next
The column list is where data types go, and the same list is where constraints attach. The next chapter looks at how to choose the data type for each column. After that, the chapters on NOT NULL, PRIMARY KEY, UNIQUE, FOREIGN KEY, and CHECK turn these bare tables into ones that reject invalid data.
Exercise
A setup script contains CREATE TABLE IF NOT EXISTS products (product_id INTEGER, name VARCHAR(100));. The database already has a products table with the columns product_id and title. What happens when the script runs, and why can that be a problem?
Show answer
The statement succeeds without changing anything, because IF NOT EXISTS checks only whether a table with that name exists. The existing table keeps its title column and gets no name column. Later statements that use name fail, or work on the wrong structure. The script reports no mismatch, so you must compare the definitions yourself or alter the table.
Exercise
You run CREATE TABLE customers_archive AS SELECT customer_id, email FROM customers;. Which parts of the original customers table definition are not carried over to the new table?
Show answer
Constraints, defaults, and indexes are not copied. Only the column names, their types, and the selected rows come across. You have to add primary keys, NOT NULL, and any other rules to the new table afterward.