CREATE TABLE, Data Types and Constraints
CREATE TABLE makes a new table. For each column you give a name, a data type and optional constraints (rules).
Designing tables decides how good your data will be for years. Each column has a type, and constraints - PRIMARY KEY, NOT NULL, UNIQUE, CHECK, FOREIGN KEY - make the database itself refuse bad data, so mistakes in app code can't corrupt it.
Example
CREATE TABLE reviews (
id INTEGER PRIMARY KEY,
product_id INTEGER NOT NULL REFERENCES products(id),
rating INTEGER CHECK (rating BETWEEN 1 AND 5),
comment TEXT,
created_at TEXT DEFAULT CURRENT_DATE
);
INSERT INTO reviews (product_id, rating, comment) VALUES (3, 5, 'Great sound!');
INSERT INTO reviews (product_id, rating, comment) VALUES (3, 4, 'Good battery');
SELECT product_id, rating, comment FROM reviews;
-- Result:
-- product_id | rating | comment
-- -----------+--------+-------------
-- 3 | 5 | Great sound!
-- 3 | 4 | Good battery▶ Try it yourselfCommon data types
INTEGER/INT,DECIMAL(10,2)for money,REAL/FLOATVARCHAR(100)orTEXTfor wordsDATE,TIMESTAMP,BOOLEAN
Constraints
PRIMARY KEY- a unique id for each rowNOT NULL- must have a valueUNIQUE- no two rows may share the value (like email)CHECK- a rule the value must passDEFAULT- the value used when none is givenREFERENCES(foreign key) - must match an id in another table
Changing a table
Example
ALTER TABLE customers ADD COLUMN phone TEXT;
DROP TABLE reviews; -- deletes the whole table, data and allSQLite is relaxed about types. MySQL and PostgreSQL are strict, so pick types carefully there - for example
DECIMAL, not FLOAT, for money.Key points
- CREATE TABLE defines columns and their types.
- A primary key uniquely identifies each row.
- Constraints (NOT NULL, UNIQUE, CHECK, FOREIGN KEY) protect data quality.
📝 Test yourself
1. Which constraint makes sure each email appears once?
2. What is a foreign key?
3. Fill in the constraint for the row's unique id:
id INTEGER KEY
