Module 00 · lesson 6

The primary key: how to tell rows apart

GadgetHub has two products with the same name, Cotton T-Shirt — from different suppliers. How can the founder point to ONE specific one without mixing them up? They need a reliable identifier.

The problem: identical names

A name isn't always unique — two products can share the same one. So how do you point to exactly ONE row? You need a guaranteed unique identifier.

The primary key

A primary key (PRIMARY KEY) is a column that uniquely identifies each row. In products that's id.

It is:

  • unique — there can't be two rows with the same id;
  • not empty — id always has a value (never NULL; you'll learn what NULL is in the next lesson);
  • stable — once set, it isn't changed.

Thanks to id you can say "product #7" for certain, even if there are ten products with the same name. Usually id is assigned automatically: the DBMS hands out the next number itself (the SERIAL type), so you don't have to think about it.

id name 5 Electric Kettle 1.7L 6 Cotton T-Shirt 7 Run+ Sneakers Cotton T-Shirt 14 … … PRIMARY KEY унікальний · не NULLunique · not NULL único · no NULL однакова назва —same name — mismo nombre — різні iddifferent id distinto id

See for yourself

The task has a query that outputs id and name, sorted by id. Look: two products are named Cotton T-Shirt, but their ids differ — it's the id that tells them apart.

Summary

  • A PRIMARY KEY / id lets you find any row unambiguously — even when names repeat.
  • Unique, not NULL, stable.
  • id is usually generated automatically (SERIAL).