Interview kitsBlog

Your dream job? Lets Git IT.
Interactive technical interview preparation platform designed for modern developers.

XGitHub

Platform

  • Categories

Resources

  • Blog
  • About the app
  • FAQ
  • Feedback

Legal

  • Privacy Policy
  • Terms of Service

© 2026 LetsGit.IT. All rights reserved.

LetsGit.IT/Categories/Databases
Databaseseasy

Primary key vs unique constraint vs index — what’s the difference?

Tags
#primary-key#unique#index#constraints
Back to categoryPractice quiz

Answer

A primary key uniquely identifies a row (and can be referenced by FKs). A unique constraint also enforces uniqueness, but isn’t “the” row identity. An index is a data structure that speeds up reads; it may be unique or not.

Advanced answer

Deep dive

These are related but not the same:

  • **Primary key (PK)**: the table’s chosen row identifier. It implies **uniqueness** and typically **NOT NULL**. You can have only one PK per table, and other tables commonly reference it via foreign keys.
  • **Unique constraint**: a rule that a column (or set of columns) must be unique. You can have many unique constraints per table and they often represent business identifiers (email, externalId, etc.).
  • **Index**: a physical data structure (often a B-tree) that makes reads faster (lookups, joins, ordering). Indexes can be unique or non-unique.

Important nuance

In many databases, PK and unique constraints are enforced using an underlying **unique index**, but the *constraint* is the semantic rule and the *index* is the access path the query planner can use.

Practical tips

  • Use PK for stable identity (surrogate id is common).
  • Use unique constraints for business rules (e.g., `(tenantId, email)` unique).
  • Add indexes to match query patterns (filters + join columns + ordering).

Common pitfalls

  • Adding indexes “just in case” (slower writes, more storage).
  • Forgetting composite uniqueness in multi-tenant schemas.
  • Assuming a constraint automatically optimizes all queries (index design still matters).

Related questions

Databases
Primary key vs unique constraint: what’s the difference?
#database#constraints#primary-key
Databases
Constraints vs triggers — what’s the difference and what do you prefer for integrity?
#constraints#triggers#integrity
Databases
What is a composite (multi-column) index and when does it help?
#index#composite-index#performance
Databases
What is a covering index?
#index#covering-index#performance
Databases
What is a foreign key and what does it enforce?
#foreign-key#constraints#integrity
Databases
What does an index do and what is the main trade-off?
#index#performance#tradeoffs