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 —
idalways has a value (neverNULL; you'll learn whatNULLis 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.
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/idlets you find any row unambiguously — even when names repeat. - Unique, not
NULL, stable. idis usually generated automatically (SERIAL).