⚡0 XP🔥0

Creating Tables and Constraints (DDL)

Lesson 7 of 10 ⏱ 5 min read ✎ 2 exercises ❓ 4-question quiz ▶ Runs SQL

CREATE TABLE with data types, PRIMARY KEY, FOREIGN KEY, UNIQUE, NOT NULL, CHECK and DEFAULT constraints, AUTOINCREMENT, ALTER TABLE, DROP and TRUNCATE.

So far you have queried tables that already existed. DDL (Data Definition Language) creates and changes the structure itself: CREATE, ALTER, DROP.

CREATE TABLE#

CREATE TABLE table_name (
    column1 datatype constraints,
    column2 datatype constraints,
    ...
    table_constraints
);
▶ Try it YourselfSQL
Ctrl + Enter to run

This try-it has no database attached - it starts empty, so you can create anything you like.

Data types#

Concept SQLite MySQL PostgreSQL
whole number INTEGER INT, BIGINT INTEGER, BIGINT
exact decimal (money) NUMERIC DECIMAL(10,2) NUMERIC(10,2)
floating point REAL FLOAT, DOUBLE REAL, DOUBLE PRECISION
short text TEXT VARCHAR(100) VARCHAR(100), TEXT
date / time TEXT ('YYYY-MM-DD') DATE, DATETIME DATE, TIMESTAMP
true/false INTEGER 0/1 BOOLEAN (TINYINT) BOOLEAN
Note

SQLite is relaxed about types (it uses "type affinity"), while MySQL and PostgreSQL enforce them strictly. Always choose the right type anyway - use DECIMAL/NUMERIC for money, never FLOAT.

Constraints - rules the database enforces#

Constraint Rule
PRIMARY KEY unique + not null; identifies each row
NOT NULL a value is required
UNIQUE no two rows may have the same value
CHECK (condition) every row must satisfy the condition
DEFAULT value used when no value is given
FOREIGN KEY ... REFERENCES the value must exist in the parent table

Constraints protect data quality no matter which application writes the data. Watch them reject bad rows:

▶ Try it YourselfSQL
Ctrl + Enter to run

The third insert fails with a UNIQUE constraint failed error - the composite key (roll, subject) already exists. Change it to (2, 'SQL', 91) and run again. Then try a score of 105 to see the CHECK constraint.

हिंदी में समझें

Constraints database के नियम हैं, जो गलत data को अंदर आने ही नहीं देते: NOT NULL (खाली नहीं छोड़ सकते), UNIQUE (दोहराव नहीं), CHECK (शर्त पूरी होनी चाहिए, जैसे marks 0-100), PRIMARY KEY (हर row की पहचान) और FOREIGN KEY (दूसरी table में वो value मौजूद होनी चाहिए)।

Foreign keys and referential integrity#

▶ Try it YourselfSQL
Ctrl + Enter to run

ON DELETE decides what happens to child rows when a parent row is deleted:

  • RESTRICT / NO ACTION (default) - refuse to delete a parent that still has children.
  • CASCADE - delete the children too.
  • SET NULL - keep the children but set the FK to NULL.

AUTOINCREMENT / identity columns#

An INTEGER PRIMARY KEY in SQLite gets the next number automatically when you leave it out. Other databases spell it differently:

SQLite MySQL PostgreSQL SQL Server
id INTEGER PRIMARY KEY id INT AUTO_INCREMENT PRIMARY KEY id SERIAL PRIMARY KEY or GENERATED ALWAYS AS IDENTITY id INT IDENTITY(1,1) PRIMARY KEY

ALTER TABLE - change an existing table#

▶ Try it Yourselfdatabase: collegeSQL
Ctrl + Enter to run

Other common forms: ALTER TABLE t DROP COLUMN c; and ALTER TABLE old RENAME TO new;. MySQL and PostgreSQL also let you change a column's type and add constraints later (ALTER TABLE t ADD CONSTRAINT ...).

Note

Every try-it starts from a fresh copy of the college database, so changes like these never break the other examples.

DROP and TRUNCATE#

DROP TABLE IF EXISTS trainees;   -- removes the table and all its data permanently
DELETE FROM trainees;            -- removes all rows, keeps the table (DML, can be rolled back)
TRUNCATE TABLE trainees;         -- MySQL/PostgreSQL: fast "delete all rows" (not in SQLite)
Common Mistake

DROP TABLE cannot be undone in most databases (outside a transaction). In real projects, take a backup and double-check the database you are connected to before running DDL.

Summary#

  • CREATE TABLE defines columns, types and constraints; use the right type (DECIMAL for money).
  • Constraints (PRIMARY KEY, NOT NULL, UNIQUE, CHECK, DEFAULT, FOREIGN KEY) keep data valid.
  • Foreign keys enforce relationships; ON DELETE CASCADE / SET NULL control what happens to children.
  • ALTER TABLE changes structure; DROP deletes a table; DELETE/TRUNCATE remove rows.

Practice Exercises

Write your code, then press Check. Your program is tested automatically.

1

Create a books table

Create a table books with: book_id INTEGER primary key, title TEXT not null, author TEXT, price REAL that must be greater than 0, and copies INTEGER defaulting to 1. Insert ('Let Us C', 'Yashavant Kanetkar', 399) and ('Head First Java', 'Kathy Sierra', 650, 3) and finally SELECT * FROM books;.

2

Add a column

Add a column phone (TEXT) to departments, set it to '0731-2550000' for the Computer Science department (dept_id 1), then show dept_id, name, phone for all departments.

Database: college (see the tables in this lesson)

Quick Quiz

Q1.

Which constraint stops a column from containing duplicates?

Q2.

What does a FOREIGN KEY constraint prevent?

Q3.

What is the difference between DROP TABLE and DELETE FROM table?

Q4.

CHECK (marks BETWEEN 0 AND 100) does what?