What Is a Key?

In a table, a key is a rule for identifying or linking rows. There are many types of keys, but in SQL 101, we will focus on the Primary Key.


Primary Key

A unique identifier for each row.

Rules:

  • Must be unique (no duplicates)
  • Cannot be empty (no nulls)
  • Only one Primary Key is allowed per table

Example:

CREATE TABLE users (
    id INTEGER PRIMARY KEY,
    name TEXT,
    age INTEGER
);

Composite Primary Key

A key used when a single column is not enough to uniquely identify a row.

Example:

CREATE TABLE scores (
	id INTEGER,
	subject TEXT,
	score INTEGER,
	
	PRIMARY KEY (id, subject)
);

In this table, student ‘A’ might have a score for Science and another for Math. Since the student ID alone is not enough to distinguish the rows, we need the “subject” information as well. So, we combine multiple columns to form the Primary Key.

Now let’s move on to reading data from our tables.