FeaturePrimary KeySecondary Key
DefinitionA unique identifier for each record in a tableA non-unique key used for searching or filtering data
UniquenessMust be unique for every recordCan be non-unique
Null ValuesNot allowed (must always have a value)Allowed (can contain nulls depending on use)
IndexingCreates a unique index: clustered in InnoDB/SQL Server, plain B-tree on a heap in PostgresCreates a non-clustered index
PurposeEnsures entity integrityUsed to optimize queries and access patterns
Can be Composite?Yes, can be made of multiple columnsYes, can also be composite
Example Use Caseid in a Users table (a unique email is a candidate/alternate key: enforce with UNIQUE)department_id in an Employees table used to filter employees by department
ExistenceMandatory for every table (usually one per table)Optional (can have multiple secondary keys in one table)
ModifiabilityTypically not changed after creationCan be added or modified based on query requirements

Example

Table:

Employees

emp_id (PK)nameemaildepartment_id (Secondary Key)
101Alicealice@email.com10
102Bobbob@email.com20
103Carolcarol@email.com10
  • Primary Key: emp_id → uniquely identifies each employee.
  • Secondary Key: department_id → used to filter or search for employees by department.

Summary

  • Use a Primary Key to uniquely identify records and ensure data integrity.
  • Use Secondary Keys (or secondary indexes) to improve performance on read queries, filters, and lookups that don’t involve the primary key.