Database Tables and Keys · Lesson 16 of 112

Database Schemas and Naming

What you will learn

  • What a schema is and how to read it
  • The difference between schema and data
  • How to change a table with ALTER TABLE
  • Habits for naming tables and columns

1. Schema versus data

The schema is the blueprint: which tables exist, their columns, types, keys and constraints. The data is the rows inside. You design the schema first, then the data fills it. A schema changes rarely and carefully; data changes all the time.

(The word schema is also used by some systems for a named group of tables inside one database, like a folder. Which meaning is used depends on the system; in this lesson it means the blueprint.)

2. Reading the schema in SQLite

This lesson runs on the sample database you chose in lesson 4.1 (use the Example data picker at the top). It uses the real tables and a few small tables of its own in your browser's copy; run the examples from top to bottom, and press Reset data to start again.

SQLite keeps the CREATE statements in a built-in table called sqlite_master. Every table of the sample database is listed there:

SELECT name FROM sqlite_master WHERE type = 'table' ORDER BY name;
name
-----------
categories
customers
employees
order_items
orders
payments
products
reviews
suppliers
(9 rows)
SELECT name FROM sqlite_master WHERE type = 'table' ORDER BY name;
name
-------------
accounts
audit_log
branches
cards
customers
loan_payments
loans
transactions
transfers
(9 rows)
SELECT name FROM sqlite_master WHERE type = 'table' ORDER BY name;
name
-----------
assignments
attendance
courses
departments
enrollments
sections
students
submissions
teachers
(9 rows)

pragma_table_info lists the columns of one table with their type, whether they are NOT NULL, their default and whether they are part of the primary key:

SELECT name, type, "notnull", dflt_value, pk FROM pragma_table_info('products');
name         type     notnull  dflt_value  pk
-----------  -------  -------  ----------  --
product_id   INTEGER        0  NULL         1
sku          TEXT           1  NULL         0
name         TEXT           1  NULL         0
category_id  INTEGER        1  NULL         0
supplier_id  INTEGER        1  NULL         0
price        REAL           1  NULL         0
cost         REAL           1  NULL         0
stock        INTEGER        1  0            0
is_active    INTEGER        1  1            0
added_on     TEXT           1  NULL         0
(10 rows)
SELECT name, type, "notnull", dflt_value, pk FROM pragma_table_info('accounts');
name           type     notnull  dflt_value  pk
-------------  -------  -------  ----------  --
account_id     INTEGER        0  NULL         1
customer_id    INTEGER        1  NULL         0
branch_id      INTEGER        1  NULL         0
account_type   TEXT           1  NULL         0
opened_on      TEXT           1  NULL         0
status         TEXT           1  'open'       0
balance_cents  INTEGER        1  NULL         0
(7 rows)
SELECT name, type, "notnull", dflt_value, pk FROM pragma_table_info('enrollments');
name         type     notnull  dflt_value  pk
-----------  -------  -------  ----------  --
student_id   INTEGER        1  NULL         1
section_id   INTEGER        1  NULL         2
enrolled_on  TEXT           1  NULL         0
grade        REAL           0  NULL         0
(4 rows)

You can also read the exact statement that built a table. Make a small table and look it up:

CREATE TABLE tags (id INTEGER PRIMARY KEY, label TEXT NOT NULL UNIQUE);
SELECT name, sql FROM sqlite_master WHERE name = 'tags';
name  sql
----  ----------------------------------------------------------------------
tags  CREATE TABLE tags (id INTEGER PRIMARY KEY, label TEXT NOT NULL UNIQUE)
(1 row)
CREATE TABLE tags (id INTEGER PRIMARY KEY, label TEXT NOT NULL UNIQUE);
SELECT name, sql FROM sqlite_master WHERE name = 'tags';
name  sql
----  ----------------------------------------------------------------------
tags  CREATE TABLE tags (id INTEGER PRIMARY KEY, label TEXT NOT NULL UNIQUE)
(1 row)
CREATE TABLE tags (id INTEGER PRIMARY KEY, label TEXT NOT NULL UNIQUE);
SELECT name, sql FROM sqlite_master WHERE name = 'tags';
name  sql
----  ----------------------------------------------------------------------
tags  CREATE TABLE tags (id INTEGER PRIMARY KEY, label TEXT NOT NULL UNIQUE)
(1 row)

Reading a schema is how you learn an unfamiliar database. Other systems have their own ways to list tables (check their documentation).

3. Changing the schema

ALTER TABLE changes an existing table. Make a small table of your own with one row, then add a column and rename another:

CREATE TABLE contacts (id INTEGER PRIMARY KEY, full_name TEXT NOT NULL, email TEXT NOT NULL UNIQUE);
INSERT INTO contacts (full_name, email) VALUES ('Rina Akter', 'rina@example.com');
ALTER TABLE contacts ADD COLUMN phone TEXT;
ALTER TABLE contacts RENAME COLUMN full_name TO name;
SELECT * FROM contacts;
SELECT name FROM pragma_table_info('contacts');
id  name        email             phone
--  ----------  ----------------  -----
 1  Rina Akter  rina@example.com  NULL
(1 row)

name
-----
id
name
email
phone
(4 rows)
CREATE TABLE contacts (id INTEGER PRIMARY KEY, full_name TEXT NOT NULL, email TEXT NOT NULL UNIQUE);
INSERT INTO contacts (full_name, email) VALUES ('Rina Akter', 'rina@example.com');
ALTER TABLE contacts ADD COLUMN phone TEXT;
ALTER TABLE contacts RENAME COLUMN full_name TO name;
SELECT * FROM contacts;
SELECT name FROM pragma_table_info('contacts');
id  name        email             phone
--  ----------  ----------------  -----
 1  Rina Akter  rina@example.com  NULL
(1 row)

name
-----
id
name
email
phone
(4 rows)
CREATE TABLE contacts (id INTEGER PRIMARY KEY, full_name TEXT NOT NULL, email TEXT NOT NULL UNIQUE);
INSERT INTO contacts (full_name, email) VALUES ('Rina Akter', 'rina@example.com');
ALTER TABLE contacts ADD COLUMN phone TEXT;
ALTER TABLE contacts RENAME COLUMN full_name TO name;
SELECT * FROM contacts;
SELECT name FROM pragma_table_info('contacts');
id  name        email             phone
--  ----------  ----------------  -----
 1  Rina Akter  rina@example.com  NULL
(1 row)

name
-----
id
name
email
phone
(4 rows)

The new column phone is NULL in existing rows. Adding a NOT NULL column without a default would fail for tables that already have rows, because the old rows would have no value:

ALTER TABLE contacts ADD COLUMN city TEXT NOT NULL;
OperationalError: Cannot add a NOT NULL column with default value NULL
ALTER TABLE contacts ADD COLUMN city TEXT NOT NULL DEFAULT 'unknown';
SELECT name, city FROM contacts;
name        city
----------  -------
Rina Akter  unknown
(1 row)
ALTER TABLE contacts ADD COLUMN city TEXT NOT NULL;
OperationalError: Cannot add a NOT NULL column with default value NULL
ALTER TABLE contacts ADD COLUMN city TEXT NOT NULL DEFAULT 'unknown';
SELECT name, city FROM contacts;
name        city
----------  -------
Rina Akter  unknown
(1 row)
ALTER TABLE contacts ADD COLUMN city TEXT NOT NULL;
OperationalError: Cannot add a NOT NULL column with default value NULL
ALTER TABLE contacts ADD COLUMN city TEXT NOT NULL DEFAULT 'unknown';
SELECT name, city FROM contacts;
name        city
----------  -------
Rina Akter  unknown
(1 row)

Changing schemas on live systems is risky, and we return to it in lesson 8.7 (migrations). Plan the schema carefully so you do not need to rewrite it often.

4. Naming habits

Names are read far more often than they are written. Good habits:

Habit Good Poor
Say what it is ordered_on d1
One style everywhere snake_case (full_name) FullName, full-name, fullname mixed
No spaces or special characters order_items Order Items!
Table names: one thing, singular or plural, but consistent customers, orders customers, Order, tblProduct
Key columns: say what they point to customer_id cid, ref
Include the unit when it matters total_poisha, weight_kg total, weight
Avoid words the language reserves order_items a table named order or group

ORDER and GROUP are SQL keywords, so a table called order causes trouble. Names inside SQL are case-insensitive in SQLite, so do not rely on capitals to tell two names apart.

Whether table names are singular (customer) or plural (customers) is a matter of taste. Pick one and keep it.

The sample databases follow these habits: plural table names, snake_case, and a key column named after the thing it points to. pragma_foreign_key_list shows where the foreign keys of a table point:

SELECT "from" AS column_name, "table" AS points_to, "to" AS in_column FROM pragma_foreign_key_list('orders');
column_name  points_to  in_column
-----------  ---------  -----------
employee_id  employees  employee_id
customer_id  customers  customer_id
(2 rows)
SELECT "from" AS column_name, "table" AS points_to, "to" AS in_column FROM pragma_foreign_key_list('accounts');
column_name  points_to  in_column
-----------  ---------  -----------
branch_id    branches   branch_id
customer_id  customers  customer_id
(2 rows)
SELECT "from" AS column_name, "table" AS points_to, "to" AS in_column FROM pragma_foreign_key_list('sections');
column_name  points_to  in_column
-----------  ---------  ----------
teacher_id   teachers   teacher_id
course_id    courses    course_id
(2 rows)

The bank also states the unit in the name: balance_cents, amount_cents.

Worked example: tidy a messy schema

Before:

CREATE TABLE Tbl1 (ID INTEGER PRIMARY KEY, nm TEXT, d TEXT, amt INTEGER, cid INTEGER)

Nobody can tell what this is. After:

CREATE TABLE orders (
    id INTEGER PRIMARY KEY,
    customer_id INTEGER NOT NULL,
    ordered_on TEXT NOT NULL,
    total_poisha INTEGER NOT NULL CHECK (total_poisha >= 0)
)

The table says what a row is, the columns say what they hold, the key column says what it points to, and the unit is in the name. The tables are made up.

Common mistakes

  • Cryptic abbreviations (nm, amt) that only the author understands.
  • Mixed naming styles across tables.
  • Reserved words as names (order, group, select).
  • Putting the type in the name (strName, tblOrders).
  • Changing a live schema without a plan or a backup.

Key takeaways

  • The schema is the blueprint (tables, columns, types, rules); data is what fills it.
  • SQLite lets you read the schema from sqlite_master.
  • ALTER TABLE can add or rename columns; adding a NOT NULL column needs a default.
  • Name things clearly and consistently, with units, and avoid reserved words.

Practice

1. What is the difference between a schema and data?

Show answer

The schema is the structure (tables, columns, types, rules); data is the rows stored in that structure.

2. How can you see the statement that created the orders table in SQLite?

Show answer

SELECT sql FROM sqlite_master WHERE name = 'orders'

3. Why does adding a NOT NULL column without a default fail on a table that has rows?

Show answer

Existing rows would have no value for the new column, which NOT NULL forbids. Add a default.

4. Rename the column nm to a better name and say why.

Show answer

For example name or full_name: it says what the value is.

5. Why is a table called order a bad idea?

Show answer

ORDER is an SQL keyword, so statements using it can fail or need special quoting.

6. Why include poisha in a column name like total_poisha?

Show answer

It states the unit so nobody mistakes the whole number for taka.