Skip to main content

CREATE

Editorial

Introduction

CREATE is a Data Definition Language (DDL) command: it builds the structure data is kept in, such as databases, tables, indexes and views.

On this site every Run starts with a new, empty database of its own, and the course's tables sit beside it, read-only. So each block here makes the tables it uses, and ends on a SELECT that shows what it did, or on the error it is about.

Here you will:

  • create a database, and see why SQLite has no statement for it
  • create tables with columns and data types
  • add constraints, and watch SQLite refuse the rows that break them
  • create tables from a query
  • create indexes and views

CREATE DATABASE

A database holds tables and the other objects of one application.

Syntax

CREATE DATABASE database_name;

Example

CREATE DATABASE ecommerce_store;

SQLite has no CREATE DATABASE: the site answers near "DATABASE": syntax error.

SQLite Note

In SQLite a database is a file, or a database kept in memory, and a program makes one by opening it. SQLite's documentation, for a file opened to read and write: "The database is opened for reading and writing, and is created if it does not already exist." Each Run here starts with a database in memory, which is gone when the Run ends.

Checking If Database Exists

In PostgreSQL the statement creates the database, and a second one fails:

CREATE DATABASE ecommerce_store;
CREATE DATABASE ecommerce_store;
-- ERROR:  database "ecommerce_store" already exists

MySQL takes IF NOT EXISTS here. Its manual: "An error occurs if the database exists and you did not specify IF NOT EXISTS". PostgreSQL does not: CREATE DATABASE IF NOT EXISTS ecommerce_store; answers syntax error at or near "NOT".

CREATE TABLE - Basics

CREATE TABLE defines a new table: its name, and each column's name and data type.

Basic Syntax

CREATE TABLE table_name (
    column1 datatype,
    column2 datatype,
    column3 datatype
);

Example

CREATE TABLE customers (
    customer_id INTEGER,
    first_name TEXT,
    last_name TEXT,
    email TEXT,
    signup_date TEXT
);

-- The table's columns, as SQLite stored them
SELECT name, type FROM pragma_table_info('customers');

This creates a table named customers with five columns. The SELECT after it reads the columns back from SQLite: customer_id INTEGER, first_name TEXT, last_name TEXT, email TEXT and signup_date TEXT.

Common Data Types

SQLite's documentation: "Each value stored in an SQLite database (or manipulated by the database engine) has one of the following storage classes:"

Storage classHoldsExample values
INTEGERWhole numbers1, 42, -100
REALNumbers with a fraction3.14, 99.99
TEXTText'Hello', 'John Doe'
BLOBBytes, stored as givenImages, files
NULLNo valueNULL

A column is declared INTEGER, REAL, TEXT or BLOB; NULL is not a type a column is given.

SQLite Data Types

A column's type is a preference, not a rule. SQLite's documentation: "The type affinity of a column is the recommended type for data stored in that column." "Any column can still store any type of data."

-- A column's type is a preference: SQLite converts what it can
CREATE TABLE t (n INTEGER);
INSERT INTO t VALUES (42), ('42'), ('forty-two');
SELECT n, typeof(n) AS stored_as FROM t;

The text '42' was stored as the integer 42, because the text is a whole number; 'forty-two' stayed text. PostgreSQL holds a column to its type and refuses that row: invalid input syntax for type integer: "forty-two". Declare the right types anyway: they say what a column is for, and other databases hold to them.

CREATE TABLE: the anatomy of a table. Each column gets a name, a data type and, optionally, constraints. A code card, with columns headed column, data type, constraint and what it means, holds the statement CREATE TABLE employees ( id INTEGER PRIMARY KEY, name TEXT NOT NULL, email TEXT UNIQUE, salary REAL DEFAULT 0 CHECK (salary >= 0), department_id INTEGER REFERENCES departments (id) ); each constraint in its colour, and beside it what it means: PRIMARY KEY, uniquely identifies each row; NOT NULL, value is required; UNIQUE, no duplicate values; DEFAULT 0, auto-fills if not provided; CHECK (salary >= 0), must satisfy a condition; REFERENCES departments (id), foreign key: links to another table. SQLite's answer, rule by rule, from running the statement with PRAGMA foreign_keys = ON: a second row with id 1 gets UNIQUE constraint failed: employees.id; a row with no name gets NOT NULL constraint failed: employees.name; a second ana@example.com gets UNIQUE constraint failed: employees.email; a salary of -10 gets CHECK constraint failed: salary >= 0; department 9, which does not exist, gets FOREIGN KEY constraint failed, with foreign keys on (SQLite leaves them off unless asked); and a salary left out is filled in as 0. What happens: before, an empty database; after, the table structure is created with no data yet: an employees table with the columns id, name, email, salary, department_id and no rows yet. CREATE TABLE defines the blueprint; INSERT fills it with data.

Column Constraints

Constraints are rules a table keeps. A row that breaks one is refused, and SQLite says which rule it broke.

PRIMARY KEY

Uniquely identifies each row in the table. No two rows can have the same primary key value.

CREATE TABLE customers (
    customer_id INTEGER PRIMARY KEY,
    first_name TEXT,
    last_name TEXT
);

INSERT INTO customers VALUES (1, 'Ana', 'Silva');
INSERT INTO customers VALUES (1, 'Bruno', 'Costa');

The second row repeats customer_id 1, and SQLite answers UNIQUE constraint failed: customers.customer_id. A column declared INTEGER PRIMARY KEY is SQLite's own number for the row. Its documentation: "if a rowid table has a primary key that consists of a single column and the declared type of that column is "INTEGER" in any mixture of upper and lower case, then the column becomes an alias for the rowid." Declared INT PRIMARY KEY, the column is an ordinary one with a unique index.

NOT NULL

Every row must have a value for this column.

CREATE TABLE products (
    product_id INTEGER PRIMARY KEY,
    product_name TEXT NOT NULL,
    price REAL NOT NULL
);

INSERT INTO products VALUES (1, NULL, 10.0);

SQLite answers NOT NULL constraint failed: products.product_name.

UNIQUE

All values in the column are different. Unlike PRIMARY KEY, a table can have many UNIQUE columns.

CREATE TABLE users (
    user_id INTEGER PRIMARY KEY,
    username TEXT UNIQUE,
    email TEXT UNIQUE
);

INSERT INTO users VALUES (1, 'ana', 'ana@example.com');
INSERT INTO users VALUES (2, 'bruno', 'ana@example.com');

The second user repeats the first one's email: UNIQUE constraint failed: users.email. Two NULLs do not count as the same value here: "For the purposes of UNIQUE constraints, NULL values are considered distinct from all other values, including other NULLs."

DEFAULT

Gives a column a value when an INSERT leaves it out.

CREATE TABLE orders (
    order_id INTEGER PRIMARY KEY,
    order_date TEXT DEFAULT CURRENT_TIMESTAMP,
    status TEXT DEFAULT 'pending'
);

-- Only the id is given: the other two take their defaults
INSERT INTO orders (order_id) VALUES (1);
SELECT * FROM orders;

Only order_id was given. status took 'pending', and order_date took the moment of the insert, written YYYY-MM-DD HH:MM:SS. SQLite's documentation: "If the default value of a column is CURRENT_TIME, CURRENT_DATE or CURRENT_TIMESTAMP, then the value used in the new row is a text representation of the current UTC date and/or time."

CHECK

Defines a condition that values must satisfy.

CREATE TABLE products (
    product_id INTEGER PRIMARY KEY,
    product_name TEXT NOT NULL,
    price REAL CHECK (price > 0),
    quantity INTEGER CHECK (quantity >= 0)
);

INSERT INTO products VALUES (1, 'pen', 0, 5);

A price of 0 breaks CHECK (price > 0): CHECK constraint failed: price > 0.

FOREIGN KEY Constraint

A foreign key ties a column to the primary key of another table: every value in it must be a key the other table has.

Syntax

CREATE TABLE child_table (
    column1 datatype,
    column2 datatype,
    FOREIGN KEY (column2) REFERENCES parent_table (parent_column)
);

Example

CREATE TABLE customers (
    customer_id INTEGER PRIMARY KEY,
    name TEXT NOT NULL
);

CREATE TABLE orders (
    order_id INTEGER PRIMARY KEY,
    order_date TEXT,
    customer_id INTEGER,
    FOREIGN KEY (customer_id) REFERENCES customers (customer_id)
);

-- Customer 99 does not exist
INSERT INTO orders VALUES (1, '2018-01-15', 99);
SELECT * FROM orders;

There is no customer 99, and SQLite kept the order anyway. Its documentation: "Foreign key constraints are disabled by default (for backwards compatibility), so must be enabled separately for each database connection."

SQLite Foreign Key Support

The same tables, with foreign keys switched on first:

PRAGMA foreign_keys = ON;

CREATE TABLE customers (
    customer_id INTEGER PRIMARY KEY,
    name TEXT NOT NULL
);

CREATE TABLE orders (
    order_id INTEGER PRIMARY KEY,
    order_date TEXT,
    customer_id INTEGER,
    FOREIGN KEY (customer_id) REFERENCES customers (customer_id)
);

INSERT INTO orders VALUES (1, '2018-01-15', 99);

Now the order for customer 99 is refused: FOREIGN KEY constraint failed. Run PRAGMA foreign_keys = ON; before the statements that need it, in every Run.

ON DELETE and ON UPDATE Actions

An action says what happens to the child rows when their parent row is deleted or its key changes:

PRAGMA foreign_keys = ON;

CREATE TABLE customers (
    customer_id INTEGER PRIMARY KEY,
    name TEXT NOT NULL
);

CREATE TABLE orders (
    order_id INTEGER PRIMARY KEY,
    customer_id INTEGER,
    FOREIGN KEY (customer_id) REFERENCES customers (customer_id)
        ON DELETE CASCADE
        ON UPDATE CASCADE
);

INSERT INTO customers VALUES (1, 'Ana'), (2, 'Bruno');
INSERT INTO orders VALUES (10, 1), (11, 1), (12, 2);

-- Customer 1 is deleted, and that customer's orders go too
DELETE FROM customers WHERE customer_id = 1;
SELECT * FROM orders;

Deleting customer 1 deleted that customer's orders, 10 and 11, too; order 12, customer 2's, is the only one left.

ActionEffect
CASCADEDeletes or updates the child rows with their parent
SET NULLSets the child rows' key to NULL
SET DEFAULTSets the child rows' key to the column's default
RESTRICTRefuses to delete or change a parent that has child rows
NO ACTIONNo special action; the foreign key still refuses a missing parent (the default)

SQLite's documentation: "A "CASCADE" action propagates the delete or update operation on the parent key to each dependent child key." "If an action is not explicitly specified, it defaults to "NO ACTION"."

CREATE TABLE with Multiple Constraints

A column can carry several constraints, and some constraints cover several columns.

Column-Level Constraints

CREATE TABLE employees (
    employee_id INTEGER PRIMARY KEY,
    first_name TEXT NOT NULL,
    last_name TEXT NOT NULL,
    email TEXT UNIQUE NOT NULL,
    hire_date TEXT DEFAULT CURRENT_DATE,
    salary REAL CHECK (salary > 0) NOT NULL,
    department_id INTEGER
);

INSERT INTO employees (employee_id, first_name, last_name, email, salary)
VALUES (1, 'Ana', 'Silva', 'ana@example.com', 0);

A salary of 0 breaks CHECK (salary > 0): CHECK constraint failed: salary > 0.

Table-Level Constraints

A constraint on several columns is written after the columns, as its own line.

CREATE TABLE order_items (
    order_id INTEGER,
    product_id INTEGER,
    quantity INTEGER CHECK (quantity > 0),
    price REAL CHECK (price >= 0),
    PRIMARY KEY (order_id, product_id)
);

INSERT INTO order_items VALUES (1, 7, 2, 9.9);
INSERT INTO order_items VALUES (1, 8, 1, 4.5);
INSERT INTO order_items VALUES (1, 7, 5, 9.9);

The composite primary key (order_id, product_id) means the pair must be unique: product 8 in order 1 is new, and the third row repeats product 7 in order 1: UNIQUE constraint failed: order_items.order_id, order_items.product_id.

CREATE TABLE IF NOT EXISTS

Creating a table that already exists is an error:

CREATE TABLE audit_log (log_id INTEGER PRIMARY KEY);
CREATE TABLE audit_log (log_id INTEGER PRIMARY KEY);

SQLite answers table audit_log already exists. IF NOT EXISTS makes the statement do nothing instead.

Syntax

CREATE TABLE IF NOT EXISTS table_name (
    column1 datatype,
    column2 datatype
);

Example

CREATE TABLE audit_log (
    log_id INTEGER PRIMARY KEY,
    action TEXT NOT NULL
);

-- A second time: IF NOT EXISTS makes it do nothing
CREATE TABLE IF NOT EXISTS audit_log (
    log_id INTEGER PRIMARY KEY,
    action TEXT NOT NULL
);

SELECT name, type FROM sqlite_master WHERE name = 'audit_log';

The second statement made nothing and raised no error: the database holds one audit_log. This helps in scripts that might be run more than once.

CREATE TABLE AS SELECT (CTAS)

A query's rows can become a new table. This is called CTAS (Create Table As Select).

Syntax

CREATE TABLE new_table AS
SELECT column1, column2
FROM existing_table
WHERE condition;

Example

CREATE TABLE sp_customers AS
SELECT customer_id, customer_city, customer_state
FROM olist_customers_dataset
WHERE customer_state = 'SP';

SELECT COUNT(*) AS customers FROM sp_customers;

The new table sp_customers holds the 41,746 customers from São Paulo state (SP), copied out of the course's table.

Use Cases for CTAS

  1. Creating backup copies of tables
  2. Filtering data into separate tables
  3. Aggregating data into summary tables
  4. Joining data from multiple tables into one
  5. Creating snapshots of data at a point in time

Note on Constraints

SQLite's documentation: "A table created using CREATE TABLE AS has no PRIMARY KEY and no constraints of any kind." Here is the statement SQLite wrote for the new table:

CREATE TABLE sp_customers AS
SELECT customer_id, customer_city, customer_state
FROM olist_customers_dataset
WHERE customer_state = 'SP';

-- The statement SQLite wrote for the new table
SELECT sql FROM sqlite_master WHERE name = 'sp_customers';

The three columns are TEXT, as in the course's table, and the new table has no key and no constraint. Add the keys and rules you need with a CREATE TABLE of your own, then fill it with INSERT.

CREATE INDEX

An index is a sorted copy of one or more columns that lets SQLite find rows without reading the whole table.

Basic Syntax

CREATE INDEX index_name ON table_name (column_name);

Example

CREATE TABLE sp_customers AS
SELECT customer_id, customer_city FROM olist_customers_dataset
WHERE customer_state = 'SP';

CREATE INDEX idx_sp_city ON sp_customers (customer_city);

SELECT name, tbl_name FROM sqlite_master WHERE type = 'index';

SQLite lists the new index idx_sp_city on sp_customers. The index goes on a table the block made, because the course's tables are read-only here. An index on one of them is refused:

CREATE INDEX idx_city ON olist_customers_dataset (customer_city);

SQLite looked for the table in the Run's own database, where it is not: no such table: main.olist_customers_dataset. The course's tables are attached under the name ecom, and an index made there is a write:

CREATE INDEX ecom.idx_city ON olist_customers_dataset (customer_city);

SQLite answers attempt to write a readonly database. Those tables already come with 8 indexes, among them idx_customers_state and idx_orders_status.

Unique Index

CREATE TABLE users (
    user_id INTEGER PRIMARY KEY,
    email TEXT
);
CREATE UNIQUE INDEX idx_email ON users (email);

INSERT INTO users VALUES (1, 'ana@example.com');
INSERT INTO users VALUES (2, 'ana@example.com');

A unique index refuses a second copy of a value, as a UNIQUE column does: UNIQUE constraint failed: users.email. SQLite's documentation: "Any attempt to insert a duplicate entry will result in an error."

Composite Index

CREATE TABLE sp_customers AS
SELECT customer_id, customer_city, customer_state FROM olist_customers_dataset
WHERE customer_state = 'SP';

CREATE INDEX idx_city_state ON sp_customers (customer_city, customer_state);

SELECT seqno, name FROM pragma_index_info('idx_city_state');

A composite index spans several columns, in the order written: first customer_city, then customer_state. It helps when a query filters on both.

When to Create Indexes

Good candidates for indexing:

  • Columns often used in WHERE
  • Columns used in JOIN conditions
  • Columns used in ORDER BY
  • Foreign key columns. SQLite's documentation: "Indices are not required for child key columns but they are almost always beneficial."

Indexes that do not pay:

  • An index on a column with few different values helps only for its rare values. Through the course's index on order_status, SQLite found the newest 10 canceled orders (625 of 99,441) in 1.33 ms, and the newest 10 delivered ones (96,478) in 20.38 ms, longer than reading and sorting every order takes (13.93 ms). Each time is the median of seven runs on the site's SQLite.
  • Columns that queries rarely use
  • Very small tables

Every index is also updated whenever rows are added or removed, or its columns change.

CREATE VIEW

A view is a saved query that can be read like a table. It stores the query, not the rows: each read runs it again.

Syntax

CREATE VIEW view_name AS
SELECT column1, column2
FROM table_name
WHERE condition;

Example

A view of the orders worth more than 1,000:

CREATE VIEW high_value_orders AS
SELECT
    o.order_id,
    o.customer_id,
    SUM(oi.price) AS total_value
FROM olist_orders_dataset AS o
JOIN olist_order_items_dataset AS oi ON o.order_id = oi.order_id
GROUP BY o.order_id, o.customer_id
HAVING SUM(oi.price) > 1000;

SELECT COUNT(*) AS orders FROM high_value_orders;

A view kept in the Run's own database looks for its tables there, and the course's are not there. Naming their database makes SQLite say why:

CREATE VIEW high_value_orders AS
SELECT
    o.order_id,
    o.customer_id,
    SUM(oi.price) AS total_value
FROM ecom.olist_orders_dataset AS o
JOIN ecom.olist_order_items_dataset AS oi ON o.order_id = oi.order_id
GROUP BY o.order_id, o.customer_id
HAVING SUM(oi.price) > 1000;

SELECT COUNT(*) AS orders FROM high_value_orders;

SQLite answers view high_value_orders cannot reference objects in database ecom. A temporary view has no such limit. SQLite's documentation: "If the "TEMP" or "TEMPORARY" keyword occurs in between "CREATE" and "VIEW" then the view that is created is only visible to the database connection that created it and is automatically deleted when the database connection is closed."

CREATE TEMP VIEW high_value_orders AS
SELECT
    o.order_id,
    o.customer_id,
    SUM(oi.price) AS total_value
FROM olist_orders_dataset AS o
JOIN olist_order_items_dataset AS oi ON o.order_id = oi.order_id
GROUP BY o.order_id, o.customer_id
HAVING SUM(oi.price) > 1000;

SELECT COUNT(*) AS orders FROM high_value_orders;

943 orders are worth more than 1,000.

Using Views

A view is read like a table:

CREATE TEMP VIEW high_value_orders AS
SELECT
    o.order_id,
    o.customer_id,
    SUM(oi.price) AS total_value
FROM olist_orders_dataset AS o
JOIN olist_order_items_dataset AS oi ON o.order_id = oi.order_id
GROUP BY o.order_id, o.customer_id
HAVING SUM(oi.price) > 1000;

SELECT *
FROM high_value_orders
WHERE customer_id = '1617b1357756262bfa56ab541c47bc16';

This customer placed the dearest order: 03caa2c082116e1d31e67e9ae3700499, worth 13,440.

Benefits of Views

  1. Simpler queries: a long query is written once and read by its name
  2. Only what is needed: a view can show some columns and leave the rest out
  3. Abstraction: readers do not need to know the tables behind it
  4. Consistency: everyone uses the same logic

Practice

Each Run starts with an empty database, so every exercise makes its tables and ends on a SELECT or on the error it is about.

Exercise 1: Create a Simple Table

Create a table for product categories:

-- A table for product categories
CREATE TABLE IF NOT EXISTS categories (
    category_id INTEGER PRIMARY KEY,
    category_name TEXT NOT NULL,
    description TEXT
);

SELECT name, type, "notnull", pk FROM pragma_table_info('categories');

SQLite reads the columns back: category_id INTEGER, category_name TEXT and description TEXT. notnull is 1 for category_name, and pk is 1 for category_id.

Exercise 2: Create Table with Constraints

Create a table with CHECK and DEFAULT, and insert a row that leaves the quantity out:

-- An inventory table with CHECK and DEFAULT
CREATE TABLE IF NOT EXISTS inventory (
    item_id INTEGER PRIMARY KEY,
    product_name TEXT NOT NULL,
    quantity INTEGER DEFAULT 0 CHECK (quantity >= 0),
    price REAL NOT NULL CHECK (price > 0),
    last_updated TEXT DEFAULT CURRENT_TIMESTAMP
);

INSERT INTO inventory (item_id, product_name, price) VALUES (1, 'pen', 2.5);
SELECT item_id, product_name, quantity, price FROM inventory;

The row was kept with a quantity of 0, the column's default, which passes CHECK (quantity >= 0).

Exercise 3: Create Table with Foreign Key

Create a parent table and a child table with a foreign key, then add two products:

PRAGMA foreign_keys = ON;

-- The parent table first
CREATE TABLE IF NOT EXISTS suppliers (
    supplier_id INTEGER PRIMARY KEY,
    supplier_name TEXT NOT NULL,
    contact_email TEXT UNIQUE
);

-- Then the child table with its foreign key
CREATE TABLE IF NOT EXISTS products_new (
    product_id INTEGER PRIMARY KEY,
    product_name TEXT NOT NULL,
    supplier_id INTEGER,
    FOREIGN KEY (supplier_id) REFERENCES suppliers (supplier_id)
);

INSERT INTO suppliers VALUES (1, 'Papelaria Sul', 'contato@example.com');
INSERT INTO products_new VALUES (1, 'pen', 1);
INSERT INTO products_new VALUES (2, 'ink', 2);

Product 1 belongs to supplier 1, which exists. Product 2 names supplier 2, which does not, and is refused: FOREIGN KEY constraint failed.

Exercise 4: Create Table from Query (CTAS)

Create a summary table from a query:

-- A summary table made from a query
CREATE TABLE IF NOT EXISTS customer_summary AS
SELECT
    customer_state,
    COUNT(*) AS customer_count
FROM olist_customers_dataset
GROUP BY customer_state;

SELECT COUNT(*) AS states FROM customer_summary;

The new table holds one row for each of the 27 states.

Exercise 5: Verify Created Table

Make the summary table again and read it:

-- Each Run starts with an empty database: make the table again, then read it
CREATE TABLE customer_summary AS
SELECT customer_state, COUNT(*) AS customer_count
FROM olist_customers_dataset
GROUP BY customer_state;

SELECT *
FROM customer_summary
ORDER BY customer_count DESC
LIMIT 10;

Each Run starts empty, so the table is made again before it is read. SP leads with 41,746 customers.

Best Practices

Naming Conventions

  1. Use lowercase with underscores: customer_orders, not CustomerOrders
  2. Be descriptive: customer_shipping_address, not csa
  3. Pick singular or plural table names and keep to it: customer or customers, not both
  4. Prefix indexes: idx_, as every index here does

Design Guidelines

  1. Define a primary key: every table should have a unique identifier
  2. Use the right data types: do not store numbers as TEXT
  3. Add NOT NULL where a value is required
  4. Use foreign keys, and switch them on in SQLite
  5. Add indexes where they pay: on columns used in WHERE and JOIN

Common Mistakes to Avoid

MistakeBetter Approach
No primary keyDefine a PRIMARY KEY
All columns nullableUse NOT NULL for required fields
Storing calculated valuesCalculate them in queries
Too many indexesIndex only columns queries use
Reserved words as namesAvoid names like order, table, select

A table named order is refused:

CREATE TABLE order (order_id INTEGER PRIMARY KEY);

SQLite answers near "order": syntax error. The course's own table is called olist_orders_dataset.

Summary

What You Learned

  • SQLite has no CREATE DATABASE: a database is a file, or memory
  • CREATE TABLE defines a table's columns and their types
  • Constraints keep data correct: PRIMARY KEY, NOT NULL, UNIQUE, DEFAULT, CHECK, FOREIGN KEY
  • SQLite's foreign keys work only once PRAGMA foreign_keys = ON has run
  • IF NOT EXISTS makes a CREATE do nothing when the object is there
  • CREATE TABLE AS SELECT makes a table from a query, with no keys or constraints
  • CREATE INDEX helps SQLite find rows, and is updated whenever its rows change
  • CREATE VIEW saves a query to read like a table

Key Takeaways

  1. The CREATE statement builds the structure data is kept in
  2. Constraints refuse the rows that would break the rules
  3. Use IF NOT EXISTS for scripts that run more than once
  4. Indexes help queries and cost writes
  5. Views keep a query under a name

Next Up

ALTER changes a table that exists, and DROP removes one.