SQL and databases

Stage 1 · Lesson 2 of 8

Primary keys and foreign keys

Relational thinking and your setup

A is a column, or a group of columns, that identifies exactly one row. Its value must be unique, and it can never be (empty). A is a column that holds another table's primary key.

You declare it as a , a rule the database enforces, so the database refuses values that do not exist in the other table. Together, keys are how tables connect. Every order points at one customer, and the database stops you creating an order for a customer who is not there.

Keys also help speed, because the database automatically builds an index (a lookup structure) on each primary key. You will use them constantly when you learn joins in the next stages.

Common trapchoosing a primary key that can change or repeat, such as an email address or a name, or leaving foreign key constraints off and ending up with rows that point at nothing.

A question to check yourself, an AI practice session and 2 cheat sheet entries come with the full roadmap. Unlock

Resources for this stage

Start with· follow one of these

  • CourseFree
    CS50's Introduction to Databases with SQL

    Harvard University · Beginner

    Watch Lecture 0 (Querying) for the relational model; it uses SQLite, and the ideas carry straight across

  • GuideFree
    PostgreSQL Tutorial

    PostgreSQL Global Development Group · Beginner

    The short official tutorial: Chapters 1 and 2 cover creating a database and your first tables

Keep handy

  • Read the installation and psql pages for your platform, and bookmark the SQL commands reference

  • A one-page map of SQL topics: use it to see where each stage of this roadmap fits

Mark this stage as not done?