Find a course

Module 5: Creating and Changing DataLesson 10 of 1112 min

Creating Tables: Data Types and Constraints

Create tables with CREATE TABLE, choose sensible data types, and protect data quality with NOT NULL, UNIQUE, CHECK, DEFAULT and foreign key constraints.

Step 1 of 13Learn

Defining a table

So far you've queried tables that already existed. CREATE TABLE defines a new one: its name, its columns, each column's data type, and the rules the data must follow.

CREATE TABLE authors (
  author_id   INTEGER PRIMARY KEY,
  name        VARCHAR(100) NOT NULL,
  country     VARCHAR(60),
  birth_year  INTEGER,
  email       VARCHAR(255) UNIQUE
);

Common data types (names vary slightly by database):

TypeHoldsExample
INTEGERwhole numbers42
DECIMAL(p, s) or NUMERICexact decimalsDECIMAL(8, 2) for 123456.78
VARCHAR(n) / TEXTtext up to n characters / any length'Night Ferry'
DATE, TIMESTAMPdates, date and time'2026-03-15'
BOOLEANtrue or falseTRUE

Choosing types well prevents bugs:

  • Use DECIMAL for money, not FLOAT. Floating-point types store approximations in binary, so values like 0.1 can't be represented exactly. Add up enough prices and you get totals like 195.48999999. DECIMAL stores exact digits.
  • Store dates as DATE or TIMESTAMP, not text. A text column will happily accept '03/15/26', '2026-3-15' and 'March 15', and then sort them wrongly and break date arithmetic.
  • Store numbers as numbers. A zip code like 02134 is an exception: it's an identifier with a meaningful leading zero, not a quantity, so text is correct.

Other structure commands: ALTER TABLE changes an existing table, for example ALTER TABLE authors ADD COLUMN website VARCHAR(255);, and DROP TABLE deletes a table and all its data permanently.

Step 2 of 13Practice · Sort into groups

Choose the best data type for each column.

Tap an item, then tap its group (or drag it there).

Step 3 of 13Flashcards

Common column data types

Tap a card to flip it.

Step 4 of 13Note

Step 5 of 13Learn

Constraints: rules the database enforces

Constraints are rules attached to columns or tables. The database checks them on every insert and update and rejects any change that would break them. They are your first and most reliable line of defense for data quality, because they apply no matter which app, script or person writes the data.

  • PRIMARY KEY: unique and not null; identifies each row.
  • NOT NULL: the column must always have a value. A book without a title makes no sense.
  • UNIQUE: no two rows may share a value. Two customers shouldn't share an email.
  • CHECK: a custom condition. CHECK (price >= 0) blocks negative prices; CHECK (stock >= 0) blocks negative stock.
  • DEFAULT: a value used when none is given. DEFAULT CURRENT_DATE for an order date, DEFAULT 0 for stock.
  • FOREIGN KEY ... REFERENCES: values must exist in another table's key.

Here's the books table defined with constraints:

CREATE TABLE books (
  book_id   INTEGER PRIMARY KEY,
  title     VARCHAR(200) NOT NULL,
  author_id INTEGER REFERENCES authors(author_id),
  genre     VARCHAR(40),
  price     DECIMAL(8, 2) NOT NULL CHECK (price >= 0),
  year      INTEGER,
  stock     INTEGER DEFAULT 0 CHECK (stock >= 0)
);

Now INSERT INTO books (book_id, title, price) VALUES (9, 'Test', -5); fails with a CHECK violation, and a book with an author_id of 999 is rejected if no such author exists.

It's tempting to skip constraints and "validate in the app." Don't rely on that alone. Data arrives through imports, admin tools, scripts and future apps written by other people. A constraint is checked every time, for every writer.

Step 6 of 13Practice · Diagram

Constraints a table can carry

Tap each constraint to see what it rejects.

Which constraint would stop an order with a total of -5.00?

Tap the shape that answers the question, then press Check.

Constraints a table can carryParts diagram: orders table, PRIMARY KEY, FOREIGN KEY, NOT NULL, UNIQUE, CHECK, DEFAULT.orders tablePRIMARY KEYFOREIGN KEYNOT NULLUNIQUECHECKDEFAULT
orders table
PRIMARY KEY

order_id must be unique and never NULL.

FOREIGN KEY

customer_id must match an existing customer; an order for customer 999 is rejected.

NOT NULL

order_date can't be left empty.

UNIQUE

No two rows may share the value, e.g. an invoice number.

CHECK

A custom rule, e.g. CHECK (total >= 0) rejects negative totals.

DEFAULT

Fills a value when an insert leaves the column out, e.g. today's date.

Step 7 of 13Practice · Spot the mistake

This table definition is meant to store orders with a required customer, a non-negative money total and an order date that defaults to today. Which lines are problematic? Click them.

Step 8 of 13Practice · Fill in the blanks

Fill in the blanks

To stop a column from ever being empty, add the constraint NOT . To stop two rows from sharing the same email, add . To reject negative prices, add (price >= 0).

Step 9 of 13Note

Step 10 of 13Learn

Indexes and a word on performance

As tables grow from thousands to millions of rows, how the database finds rows starts to matter.

Without help, a query like SELECT * FROM orders WHERE customer_id = 4 requires a full table scan: checking every single row. An index is a separate data structure, usually a sorted tree, that lets the database jump straight to matching rows, much like the index at the back of a book lets you find a topic without reading every page.

CREATE INDEX idx_orders_customer ON orders (customer_id);

Primary keys and UNIQUE columns get indexes automatically. Good candidates for additional indexes are columns used often in WHERE filters, JOIN conditions and ORDER BY, such as foreign keys and dates.

Indexes aren't free:

  • They take extra storage.
  • They slow down inserts, updates and deletes slightly, because each index must be updated too.
  • Indexes on columns rarely used in searches are pure cost.

Some query habits prevent the database from using an index. Wrapping the column in a function, such as WHERE LOWER(email) = 'x' or WHERE YEAR(order_date) = 2026, often forces a full scan; rewriting the second as a range, WHERE order_date >= '2026-01-01' AND order_date < '2027-01-01', lets an index on order_date work. A LIKE pattern that starts with %, such as '%son', can't use a normal index either.

Most databases can show the plan they'll use for a query with EXPLAIN (EXPLAIN SELECT ...), which reveals whether an index is used or the whole table is scanned. You don't need to master query tuning as a beginner, but knowing that indexes exist explains why the same query can take a millisecond on one table and a minute on another.

Step 11 of 13Try the calculator

Full table scan vs. index lookup

A full scan checks every row. A B-tree index narrows the search step by step, so the work grows roughly with log2 of the row count. The index figure is an idealized comparison count, not a timing.

Rows checked by a full scan
1,000,000
Comparisons with an index (about)
20
Times less work
50,000

Step 12 of 13Practice · Select all that apply

Which columns are good candidates for an index in a large orders table? Select all that apply.

Select all that apply.

Step 13 of 13Practice · Choose one

Why should money amounts be stored as DECIMAL rather than FLOAT?