Reading history

SQL CREATE TABLE and Constraints (PRIMARY KEY, FOREIGN KEY)

4 min read 0 views

Learn SQL CREATE TABLE with constraints: PRIMARY KEY, NOT NULL, UNIQUE, FOREIGN KEY, CHECK and DEFAULT, plus ALTER TABLE and DROP TABLE.

Before you can store data, you need a table, and a well-designed table protects its own data. CREATE TABLE defines the columns and their types, and constraints are rules the database enforces on every insert and update: every row needs an id, emails must be unique, salaries must be positive. This lesson also covers changing and removing tables with ALTER and DROP.

In this lesson you will learn

  • The syntax of CREATE TABLE
  • Common column types
  • The six main constraints
  • How foreign keys link tables
  • How to add columns and drop tables

Creating a Table with Constraints

CREATE TABLE teachers (
    id      INTEGER PRIMARY KEY,
    name    TEXT NOT NULL,
    email   TEXT UNIQUE,
    dept    TEXT REFERENCES departments(code),
    salary  INTEGER CHECK (salary > 0),
    joined  TEXT DEFAULT '2026-01-01'
);

INSERT INTO teachers (id, name, email, dept, salary)
VALUES (1, 'Dr. Hasan', 'hasan@uni.edu', 'CSE', 95000);

SELECT * FROM teachers;

Output

+----+-----------+---------------+------+--------+------------+
| id | name      | email         | dept | salary | joined     |
+----+-----------+---------------+------+--------+------------+
| 1  | Dr. Hasan | hasan@uni.edu | CSE  | 95000  | 2026-01-01 |
+----+-----------+---------------+------+--------+------------+
(1 row)
  • Each column has a name, a type and optional constraints.
  • PRIMARY KEY identifies each row; it must be unique and not null.
  • NOT NULL forbids missing values.
  • UNIQUE forbids duplicates, ideal for emails and usernames.
  • REFERENCES departments(code) is a foreign key: dept must match an existing department.
  • CHECK (salary > 0) rejects values that break the rule.
  • DEFAULT fills in a value when none is given, which is why joined shows 2026-01-01.

ALTER TABLE and DROP TABLE

CREATE TABLE teachers (
    id INTEGER PRIMARY KEY,
    name TEXT NOT NULL,
    email TEXT UNIQUE
);
INSERT INTO teachers VALUES (1, 'Dr. Hasan', 'hasan@uni.edu');

ALTER TABLE teachers ADD COLUMN phone TEXT;
UPDATE teachers SET phone = '01700-000000' WHERE id = 1;
SELECT * FROM teachers;

DROP TABLE teachers;
SELECT COUNT(*) AS tables_named_teachers
FROM sqlite_master WHERE type = 'table' AND name = 'teachers';

Output

+----+-----------+---------------+--------------+
| id | name      | email         | phone        |
+----+-----------+---------------+--------------+
| 1  | Dr. Hasan | hasan@uni.edu | 01700-000000 |
+----+-----------+---------------+--------------+
(1 row)

+-----------------------+
| tables_named_teachers |
+-----------------------+
| 0                     |
+-----------------------+
(1 row)
  • ALTER TABLE ... ADD COLUMN adds a column to an existing table; existing rows get NULL (or the default).
  • DROP TABLE deletes the table and all its data. The final query confirms it no longer exists.
  • Other ALTER forms include RENAME COLUMN and DROP COLUMN; support varies between databases.

Common Data Types

TypeStoresNotes
INTEGER / INTWhole numbersBIGINT for very large values
DECIMAL(10,2)Exact decimalsUse for money
REAL / FLOATApproximate decimalsSmall rounding errors possible
VARCHAR(n) / TEXTTextn sets a maximum length
DATE, TIMESTAMPDates and timesSQLite stores them as text or numbers
BOOLEANTrue / falseSQLite uses 1 and 0

SQLite is flexible with types

SQLite accepts most type names and does not strictly enforce them, and it checks foreign keys only after PRAGMA foreign_keys = ON;. MySQL and PostgreSQL enforce both by default.

Common Mistakes

  1. Tables without a primary key, which makes updating one specific row unreliable.
  2. Using FLOAT for money. Use DECIMAL.
  3. Running DROP TABLE on the wrong database. There is no undo outside a transaction.
  4. Adding a NOT NULL column without a default to a table that already has rows, which most databases reject.

Practice Exercises

Exercise 1. Create a books table with an id, a required title, a unique ISBN and a price that must be zero or more.

Show answer
CREATE TABLE books (
    id    INTEGER PRIMARY KEY,
    title TEXT NOT NULL,
    isbn  TEXT UNIQUE,
    price DECIMAL(8,2) CHECK (price >= 0)
);

Exercise 2. Add a pages column to books.

Show answer
ALTER TABLE books ADD COLUMN pages INTEGER;

Frequently Asked Questions

What is the difference between a primary key and a unique constraint?

A table has only one primary key, and it can never be NULL. It can have many UNIQUE columns, which in most databases may hold NULL.

How do I create a table only if it does not exist?

Use CREATE TABLE IF NOT EXISTS teachers (...), which is supported by SQLite, MySQL and PostgreSQL.

Summary

  • CREATE TABLE defines columns, types and constraints.
  • Constraints (PRIMARY KEY, NOT NULL, UNIQUE, FOREIGN KEY, CHECK, DEFAULT) keep data valid.
  • ALTER TABLE changes a table; DROP TABLE deletes it.

Next: SQL Indexes.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *