Q1Which of the following correctly describes a primary key (PRIMARY KEY)?
Creating and Modifying Tables
Learn SQL table definitions from the ground up. Cover CREATE TABLE, PRIMARY KEY, inspecting table definitions, and adding, dropping, and renaming columns with ALTER TABLE — all running live in your browser.
About the SQL covered in this course
This course teaches the universal SQL syntax that works across major RDBMSs — MySQL, Oracle, PostgreSQL, SQL Server, and more. The basics like CREATE TABLE / SELECT / WHERE / JOIN / GROUP BY write the same way no matter which database you switch to.
For technical reasons the in-browser console runs SQLite, but whenever a feature differs between databases (length enforcement on types, how to list tables, etc.) you'll see a side-by-side note like In MySQL you'd write... so you know what to use elsewhere.
What is a table?
In a relational database, you store data in tables (grids of rows and columns). Each table consists of columns and rows (records), and each column has a fixed data type that controls what values it can hold.
Designing a table means deciding up front which columns to include and which type to assign to each one. Locking down the types prevents unexpected values from sneaking in later.
CREATE TABLE — creating a table
To create a table you use the CREATE TABLE statement. Write the table name, then in parentheses list column name + type pairs separated by commas. Don't put a comma after the last column.
Locking down types up front makes it harder for unexpected data to slip in (like a string ending up in a numeric column).
-- Create a table by listing column names and types
CREATE TABLE book_record (
id INTEGER,
title TEXT,
price INTEGER,
published_on TEXT
);
Common data types
SQL data types vary in name and detail across database systems, but starting out you only need to know the following types.
| Type | Stored values | Example use |
|---|---|---|
| INTEGER | Integers | id / age / count |
| REAL | Floating-point numbers | score / weight |
| TEXT | Strings | name / address / message |
| BLOB | Binary data | Byte streams for images, audio, etc. |
| NUMERIC | Numbers in general (incl. dates, booleans) | Doubles as date / boolean |
What about MySQL's VARCHAR / CHAR / DATETIME?
In MySQL and PostgreSQL you'll often see fine-grained types like VARCHAR(255) / CHAR(13) / BOOLEAN / DATETIME. The console here accepts these syntactically, but length enforcement (like VARCHAR(10) rejecting an 11th character) only kicks in on strict-typed RDBMSs like MySQL or PostgreSQL.
For exercises in this course, columns mostly use INTEGER / TEXT / REAL to keep things simple. When you port a definition to MySQL, you can replace INTEGER with INT and TEXT with VARCHAR(N) or TEXT — the structure of CREATE TABLE itself stays the same.
PRIMARY KEY — uniquely identifying a row
A primary key (PRIMARY KEY — a column used to uniquely identify a row) is a column where values must be unique and never NULL. You make a column the primary key when its values must always exist and never collide, like an employee number or user ID.
With a primary key in place you can reliably retrieve a single row. As a rule, every table should have exactly one primary key.
-- Add PRIMARY KEY after the column definition
CREATE TABLE member (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
joined_on TEXT
);
INTEGER PRIMARY KEY auto-numbers
A column declared as INTEGER PRIMARY KEY gets auto-numbered starting from 1 whenever you INSERT without specifying its value. In MySQL the same auto-numbering is written as id INT PRIMARY KEY AUTO_INCREMENT, and in PostgreSQL as id SERIAL PRIMARY KEY. In this course's console, INTEGER PRIMARY KEY is enough.
If you INSERT with an explicit value, that value is used, and the next auto-number resumes from the integer just after it.
Trying a constraint violation — how NOT NULL works
Let's deliberately break a rule to see how constraints (rules a column's values must obey) like NOT NULL and PRIMARY KEY work. NOT NULL is a rule that doesn't allow NULL in the column. Adding it to required fields (name, email address, etc.) prevents incomplete rows from sneaking in.
The user table created at the top of the article was defined with name TEXT NOT NULL. If you try to insert NULL into the name column, the database will reject the INSERT and return an error.
NOT NULL column is rejected with an error. Empty string ('') is treated as a different value from NULL, so an INSERT with an empty string still goes through — keep that distinction in mind.-- INSERT that triggers a NOT NULL violation in Exercise 3
INSERT INTO user (id, name, age, city)
VALUES (10, NULL, 30, 'Tokyo');
Inspecting and dropping tables
After you create a table, you'll want to check which tables exist and what columns each one has. The console here uses these two queries:
- List of tables: SELECT name FROM sqlite_master WHERE type='table';
- Column definitions: PRAGMA table_info(table_name);
In MySQL you'd write SHOW TABLES; and DESCRIBE table_name;; Oracle uses SELECT table_name FROM user_tables;. Each database has its own dedicated syntax. DROP TABLE for removing a table works the same way across all databases.
-- ① List all tables
SELECT name FROM sqlite_master WHERE type='table';
-- ② Show column definitions of the user table
PRAGMA table_info(user);
-- ③ Drop a table
DROP TABLE IF EXISTS book_record;
ALTER TABLE — modifying an existing definition
Once your system is in production, requests like "add one more column" or "rename the table" are inevitable. That's where ALTER TABLE comes in. The four operations covered here all work in MySQL and PostgreSQL with nearly identical syntax.
| Operation | Syntax | Use |
|---|---|---|
| Rename a table | ALTER TABLE old_name RENAME TO new_name; | Rename the whole table |
| Add a column | ALTER TABLE table ADD COLUMN col type; | Add a new attribute |
| Drop a column | ALTER TABLE table DROP COLUMN col; | Remove an unused attribute |
| Rename a column | ALTER TABLE table RENAME COLUMN old TO new; | Rename a column |
MySQL's MODIFY / CHANGE COLUMN / AFTER
In MySQL you can change a column's type with ALTER TABLE table MODIFY col type;, change a column's name and type at the same time with CHANGE COLUMN old new type;, and drop the primary key with DROP PRIMARY KEY;.
-- Rename the table
ALTER TABLE user RENAME TO user_record;
-- Add a column (an email column is appended to the end)
ALTER TABLE user_record ADD COLUMN email TEXT;
-- Rename a column
ALTER TABLE user_record RENAME COLUMN city TO area;
-- Drop a column
ALTER TABLE user_record DROP COLUMN email;
Knowledge Check
Answer each question one by one.
Q2What's the most appropriate way to inspect the column definitions of the user table in this course's console?
Q3Which of these correctly describes how ALTER TABLE behaves in this course's console?