Find a course

Module 1: Relational FoundationsLesson 2 of 1214 min

Tables, Keys and Constraints

Choose primary keys, compare natural and surrogate keys, pick sensible data types, handle NULL correctly, and protect data with constraints.

Step 1 of 15Learn

What makes a good primary key

Every table needs a way to point at exactly one row. That's the job of the primary key (PK). A primary key must be:

  • Unique: no two rows share the same value.
  • Not null: every row has a value.
  • Stable: it should rarely or never change, because other tables refer to it.
  • Minimal: no unnecessary columns.

Any column or column set that is unique and minimal is a candidate key. A customer table might have two candidates: a customer number and an email address. You choose one as the primary key; the others are alternate keys, which you still declare UNIQUE so the DBMS keeps them unique.

Email looks tempting as a primary key, but it fails the stability test: people change email addresses, and every order referring to the old address would need updating. Names fail uniqueness: there are many people called Ben Okafor. Phone numbers get reassigned. Rule of thumb: if a value comes from the outside world and can change or repeat, it is a poor primary key, even if you still store it and enforce its uniqueness.

Step 2 of 15Practice · Choose one

Which column is the best choice of primary key for a table of students at a university?

Step 3 of 15Diagram

The four tests for a primary key

The four tests for a primary keyParts diagram: Primary key, Unique, Not null, Stable, Minimal.Primary keyUniqueNot nullStableMinimal

Tap a shape with to see more.

Primary key
Unique

No two rows share a value. Names fail this test.

Not null

Every row has a value. Optional fields such as phone fail.

Stable

Rarely or never changes, because other tables point at it. Emails change.

Minimal

No extra columns: (student_id, name) is unique, but name adds nothing.

Step 4 of 15Learn

Natural keys and surrogate keys

A natural key is a value that already exists in the real world: an ISBN for a book, a country code like "FR," a vehicle identification number. A surrogate key is an artificial value created by the database, usually an auto-incrementing integer (1, 2, 3...) or a randomly generated UUID, with no meaning outside the system.

Many designers default to surrogate keys for main entities, for good reasons. They never need to change, they are compact (a 4- or 8-byte integer is faster to compare and index than a long string), and they protect you when the outside world breaks its own rules: ISBNs, for example, have occasionally been reused or assigned to more than one edition.

Natural keys still have their place. Small, stable code tables (currencies, countries, US state abbreviations) are often keyed naturally, which makes data readable without joins. And when you use a surrogate key, keep the natural key as a UNIQUE column. Otherwise nothing stops two rows for the same book from creeping in with different ids: the surrogate key guarantees each row is distinct, not that each real-world thing appears once.

A composite key uses two or more columns together, such as (order_id, line_number) for order lines. Composite keys are natural for tables that link other tables, which you'll meet in the next module.

Step 5 of 15Practice · Sort into groups

Classify each key.

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

Step 6 of 15Compare

Natural keys vs surrogate keys

AspectNatural keySurrogate key
ExampleISBN, country code "FR"customer_id 1, 2, 3 or a UUID
Meaning outside the databaseYesNone
Can change?Sometimes (formats get revised)Never needs to
Foreign key sizeCan be long textSmall and fast to join
Still needNothing extraA UNIQUE constraint on the real-world identifier

Step 7 of 15Learn

Choosing data types

Every column has a data type, and choosing well prevents bad data and wasted space. Common SQL types:

Kind of dataTypical typeNotes
Whole numbersINTEGER, BIGINTUse BIGINT for ids that may pass about 2.1 billion
MoneyDECIMAL(10,2) or NUMERICExact; never use floating-point types for money
MeasurementsREAL, DOUBLE PRECISIONApproximate; fine for temperatures and distances
Short textVARCHAR(n)Names, emails, codes
Long textTEXTDescriptions, comments
Dates and timesDATE, TIMESTAMPStore real dates, not text like "03/04/26"
Yes/noBOOLEANSome systems use a 0/1 integer

Two mistakes are especially common. First, money in floating-point columns. Floats store binary approximations, so 0.1 + 0.2 comes out as 0.30000000000000004. Over millions of transactions, those tiny errors show up in reports. DECIMAL stores exact decimal digits. Second, dates stored as text. "03/04/2026" means March 4 in the US and April 3 in much of Europe, text dates sort wrongly ("10/01" sorts before "9/30"), and the DBMS can't check that February 30 doesn't exist. Use DATE or TIMESTAMP and let the database handle formatting.

Phone numbers and ZIP codes look numeric but are text: they can start with zeros or contain "+", and you never do arithmetic on them.

Step 8 of 15Practice · Match the pairs

Match each column to the most suitable data type.

Tap an answer, then tap the place where it belongs (or drag it there).

  1. price of a book in dollars
  2. order_date
  3. phone_number
  4. quantity_in_stock
  5. is_gift_wrapped

Step 9 of 15Learn

NULL: the value that isn't there

NULL marks a missing or unknown value. It is not zero and not an empty string. A customer whose phone number is NULL might have no phone, or might have one that you simply don't know.

NULL follows unusual logic. Any comparison with NULL gives unknown, not true or false. So the condition phone = NULL is never true, even for rows where phone is missing; you must write phone IS NULL. Arithmetic with NULL gives NULL: price + NULL is NULL. And aggregates such as AVG skip NULLs, so the average rating of (5, 3, NULL) is 4, not 2.67.

Design decisions follow from this:

  • Mark columns NOT NULL whenever a value is truly required, such as an order's date or a customer's name. This is one of the cheapest and most effective constraints.
  • Allow NULL only where "unknown" or "not applicable" is a real possibility, such as a middle name.
  • Many NULLs in one table can signal a design problem. If a product table has 15 columns that are only filled in for books and 12 that are only filled in for music, it may really be describing several kinds of things that deserve separate tables.

Step 10 of 15Compare

Three-valued logic: how NULL behaves

AspectResultRow kept by WHERE?
phone = NULLUNKNOWNNo
phone IS NULL (phone missing)TRUEYes
5 > NULLUNKNOWNNo
TRUE AND UNKNOWNUNKNOWNNo
FALSE AND UNKNOWNFALSENo
TRUE OR UNKNOWNTRUEYes

Step 11 of 15Note

Step 12 of 15Practice · True or false

If a table's rating column contains 4, 2 and NULL, AVG(rating) returns 3.

Step 13 of 15Learn

Constraints: rules the database enforces

Application code changes, gets rewritten and has bugs. Rules declared in the database apply to every program and person that touches the data. The main constraints are:

  • PRIMARY KEY: unique and not null; identifies each row.
  • NOT NULL: the column must always have a value.
  • UNIQUE: no two rows may share a value (alternate keys such as email or ISBN).
  • CHECK: a condition each row must satisfy, such as CHECK (price >= 0) or CHECK (rating BETWEEN 1 AND 5).
  • FOREIGN KEY: a value must match an existing key in another table. You'll study these in the module on mapping relationships.
  • DEFAULT: a value used when none is supplied, such as the current date for order_date.

Constraints catch bugs at the moment bad data tries to enter, with a clear error, instead of months later when a report shows negative stock. They also document the design: anyone reading the schema learns that ratings run from 1 to 5. The cost is small: a few checks on each insert or update.

A good habit is to ask of every column: Can it be missing? Must it be unique? What values are valid? Then write those answers down as constraints.

Step 14 of 15Practice · What would you do?

What would you do?

A developer argues: "We validate every field in our web form, so database constraints like CHECK and NOT NULL are redundant." What is the strongest reply?

Step 15 of 15Practice · Choose one

A product table should never contain a negative price. Which constraint enforces this?