Creating Tables and Constraints · Lesson 41 of 64

SQL CREATE TABLE

What you will learn

  • How to write CREATE TABLE with columns and types
  • How to choose a primary key
  • How to use IF NOT EXISTS and see the table you made
  • How to turn a description into a table

This lesson runs on the sample database you chose in lesson 1.1 (use the Example data picker at the top). The tables you create exist only in your browser's copy of the data; Reset data removes them. Run the cells from top to bottom.

1. The shape of CREATE TABLE

CREATE TABLE name ( column definitions ) makes an empty table. Each column definition is a name, a type, and optional rules, separated by commas:

CREATE TABLE lib_books (
    book_id INTEGER PRIMARY KEY,
    title   TEXT NOT NULL,
    author  TEXT NOT NULL,
    year    INTEGER,
    price   REAL
);
(done)
CREATE TABLE lib_books (
    book_id INTEGER PRIMARY KEY,
    title   TEXT NOT NULL,
    author  TEXT NOT NULL,
    year    INTEGER,
    price   REAL
);
(done)
CREATE TABLE lib_books (
    book_id INTEGER PRIMARY KEY,
    title   TEXT NOT NULL,
    author  TEXT NOT NULL,
    year    INTEGER,
    price   REAL
);
(done)

Read it as: a table lib_books with an INTEGER primary key, required text columns title and author, an optional whole number year and an optional decimal price. (The prefix lib_ keeps our tables apart from the sample tables.)

The table now exists and is empty. Prove it, and look at its structure with what you learned in lesson 1.1:

SELECT COUNT(*) AS rows_in_table FROM lib_books;
rows_in_table
-------------
            0
(1 row)
SELECT cid, name, type, "notnull", pk FROM pragma_table_info('lib_books');
cid  name     type     notnull  pk
---  -------  -------  -------  --
  0  book_id  INTEGER        0   1
  1  title    TEXT           1   0
  2  author   TEXT           1   0
  3  year     INTEGER        0   0
  4  price    REAL           0   0
(5 rows)
SELECT COUNT(*) AS rows_in_table FROM lib_books;
rows_in_table
-------------
            0
(1 row)
SELECT cid, name, type, "notnull", pk FROM pragma_table_info('lib_books');
cid  name     type     notnull  pk
---  -------  -------  -------  --
  0  book_id  INTEGER        0   1
  1  title    TEXT           1   0
  2  author   TEXT           1   0
  3  year     INTEGER        0   0
  4  price    REAL           0   0
(5 rows)
SELECT COUNT(*) AS rows_in_table FROM lib_books;
rows_in_table
-------------
            0
(1 row)
SELECT cid, name, type, "notnull", pk FROM pragma_table_info('lib_books');
cid  name     type     notnull  pk
---  -------  -------  -------  --
  0  book_id  INTEGER        0   1
  1  title    TEXT           1   0
  2  author   TEXT           1   0
  3  year     INTEGER        0   0
  4  price    REAL           0   0
(5 rows)

2. Put rows in

A new table is useful only with data. You know INSERT (lesson 5.1). The primary key fills itself in:

INSERT INTO lib_books (title, author, year, price) VALUES
  ('Rain Songs', 'A. Karim', 2011, 12.5),
  ('River Maps', 'N. Das', 2018, 20.0),
  ('Night Train', 'A. Karim', 2020, NULL);
SELECT * FROM lib_books ORDER BY book_id;
book_id  title        author    year  price
-------  -----------  --------  ----  -----
      1  Rain Songs   A. Karim  2011   12.5
      2  River Maps   N. Das    2018   20.0
      3  Night Train  A. Karim  2020   NULL
(3 rows)
INSERT INTO lib_books (title, author, year, price) VALUES
  ('Rain Songs', 'A. Karim', 2011, 12.5),
  ('River Maps', 'N. Das', 2018, 20.0),
  ('Night Train', 'A. Karim', 2020, NULL);
SELECT * FROM lib_books ORDER BY book_id;
book_id  title        author    year  price
-------  -----------  --------  ----  -----
      1  Rain Songs   A. Karim  2011   12.5
      2  River Maps   N. Das    2018   20.0
      3  Night Train  A. Karim  2020   NULL
(3 rows)
INSERT INTO lib_books (title, author, year, price) VALUES
  ('Rain Songs', 'A. Karim', 2011, 12.5),
  ('River Maps', 'N. Das', 2018, 20.0),
  ('Night Train', 'A. Karim', 2020, NULL);
SELECT * FROM lib_books ORDER BY book_id;
book_id  title        author    year  price
-------  -----------  --------  ----  -----
      1  Rain Songs   A. Karim  2011   12.5
      2  River Maps   N. Das    2018   20.0
      3  Night Train  A. Karim  2020   NULL
(3 rows)

3. The primary key

Every table should have a primary key: a column whose value is unique and never empty, and identifies each row (Database Fundamentals, lesson 2.4). In SQLite a column declared exactly INTEGER PRIMARY KEY numbers itself. To make a key from two columns, write the rule after the columns:

CREATE TABLE lib_loans (
    book_id   INTEGER NOT NULL,
    member    TEXT NOT NULL,
    loaned_on TEXT NOT NULL,
    PRIMARY KEY (book_id, member, loaned_on)
);
INSERT INTO lib_loans VALUES (1, 'Rina', '2026-10-01'), (1, 'Sam', '2026-10-02');
SELECT * FROM lib_loans ORDER BY loaned_on;
book_id  member  loaned_on
-------  ------  ----------
      1  Rina    2026-10-01
      1  Sam     2026-10-02
(2 rows)
CREATE TABLE lib_loans (
    book_id   INTEGER NOT NULL,
    member    TEXT NOT NULL,
    loaned_on TEXT NOT NULL,
    PRIMARY KEY (book_id, member, loaned_on)
);
INSERT INTO lib_loans VALUES (1, 'Rina', '2026-10-01'), (1, 'Sam', '2026-10-02');
SELECT * FROM lib_loans ORDER BY loaned_on;
book_id  member  loaned_on
-------  ------  ----------
      1  Rina    2026-10-01
      1  Sam     2026-10-02
(2 rows)
CREATE TABLE lib_loans (
    book_id   INTEGER NOT NULL,
    member    TEXT NOT NULL,
    loaned_on TEXT NOT NULL,
    PRIMARY KEY (book_id, member, loaned_on)
);
INSERT INTO lib_loans VALUES (1, 'Rina', '2026-10-01'), (1, 'Sam', '2026-10-02');
SELECT * FROM lib_loans ORDER BY loaned_on;
book_id  member  loaned_on
-------  ------  ----------
      1  Rina    2026-10-01
      1  Sam     2026-10-02
(2 rows)

A book can be loaned many times, to many members, but the same member cannot loan the same book twice on the same day.

4. IF NOT EXISTS

Creating a table that exists gives an error. IF NOT EXISTS makes the statement do nothing instead, which is handy in scripts that run more than once:

CREATE TABLE lib_books (book_id INTEGER PRIMARY KEY);
OperationalError: table lib_books already exists
CREATE TABLE IF NOT EXISTS lib_books (book_id INTEGER PRIMARY KEY);
(done)
CREATE TABLE lib_books (book_id INTEGER PRIMARY KEY);
OperationalError: table lib_books already exists
CREATE TABLE IF NOT EXISTS lib_books (book_id INTEGER PRIMARY KEY);
(done)
CREATE TABLE lib_books (book_id INTEGER PRIMARY KEY);
OperationalError: table lib_books already exists
CREATE TABLE IF NOT EXISTS lib_books (book_id INTEGER PRIMARY KEY);
(done)

The second statement did nothing and the table kept its columns. (If you need to change an existing table, use ALTER TABLE, lesson 6.5.)

5. A table from a query

CREATE TABLE ... AS SELECT builds a table from a result (lesson 5.8). It has the columns and data but none of the rules:

CREATE TABLE lib_expensive AS SELECT product_id, name, price FROM products WHERE price > 40;
SELECT COUNT(*) AS rows_in_table FROM lib_expensive;
rows_in_table
-------------
            8
(1 row)
CREATE TABLE lib_big_accounts AS SELECT account_id, account_type, balance_cents FROM accounts WHERE balance_cents > 400000;
SELECT COUNT(*) AS rows_in_table FROM lib_big_accounts;
rows_in_table
-------------
            4
(1 row)
CREATE TABLE lib_heavy_courses AS SELECT course_id, code, credits FROM courses WHERE credits >= 4;
SELECT COUNT(*) AS rows_in_table FROM lib_heavy_courses;
rows_in_table
-------------
            7
(1 row)

6. Naming habits

  • Names in snake_case, plural for tables (books), singular for columns (title).
  • One idea per table; one value per cell (Database Fundamentals, chapters 5 and 10).
  • Avoid words the language reserves (order, group).
  • Put the unit in the name when it matters (price_cents).

Worked example: from a description to a table

"We keep a list of students' pets: the pet's name, its kind (dog, cat...), the year it was born (maybe unknown), and which student owns it."

Need Column
a number for each pet pet_id INTEGER PRIMARY KEY
the name, always known name TEXT NOT NULL
the kind, always known kind TEXT NOT NULL
the birth year, maybe unknown born INTEGER (can be NULL)
the owner student_id INTEGER NOT NULL (a link to students, lesson 6.3)

CREATE TABLE lib_pets (pet_id INTEGER PRIMARY KEY, name TEXT NOT NULL, kind TEXT NOT NULL, born INTEGER, student_id INTEGER NOT NULL); The description is made up.

Common mistakes

  • No primary key.
  • A comma after the last column, which is a syntax error.
  • Making everything TEXT instead of a suitable type (lesson 6.2).
  • Marking a column NOT NULL that may be unknown.
  • Creating a table that exists without IF NOT EXISTS.

Key takeaways

  • CREATE TABLE name (column type rules, ...) creates an empty table.
  • Give every table a primary key; INTEGER PRIMARY KEY numbers itself in SQLite.
  • IF NOT EXISTS avoids the error when the table is there.
  • CREATE TABLE ... AS SELECT copies data but not rules.

Practice

1. Write a table pets with an id key and a required name.

Show answer

CREATE TABLE pets (pet_id INTEGER PRIMARY KEY, name TEXT NOT NULL);

2. How do you make a primary key from two columns?

Show answer

Add PRIMARY KEY (a, b) after the column definitions.

3. What does CREATE TABLE IF NOT EXISTS t (...) do when t already exists?

Show answer

Nothing: no error, and the table is left as it was.

4. What is wrong with a comma after the last column?

Show answer

It is a syntax error; commas go only between definitions.

5. Which query shows the columns of a table in SQLite?

Show answer

SELECT * FROM pragma_table_info('table_name');

6. What does CREATE TABLE ... AS SELECT not give the new table?

Show answer

Keys, defaults and constraints.