Primary Key in Databases
Fast recall
Quick revision
Core answer
Understanding of primary key constraints (uniqueness and non-nullability), why key values should normally stay stable, and the distinction between single-column and composite primary keys
Confusing unique constraints with primary keys, or thinking a table can have multiple primary keys when only one is allowed per table
Compare stable natural keys with surrogate keys, and keep a UNIQUE constraint for any business identifier that must remain unique
Interview-ready guide
Interview answer
A primary key is one column or a group of columns that uniquely identifies a row. Its columns are unique and cannot be NULL. A table can have at most one primary-key constraint, but that key can contain several columns. For example, customers.id can be a generated surrogate key, while (order_id, product_id) can form a composite key in a junction table. A key is not made immutable by SQL, but choosing a stable value avoids difficult updates to referenced rows. In JPA, @Id marks the entity identity; a composite key can use @EmbeddedId or @IdClass.
Primary Key in Databases
Direct Answer
A primary key is one column or a group of columns that uniquely identifies a row. Its columns are unique and cannot be NULL. A table can have at most one primary-key constraint, although that key may contain several columns. Most entity tables should have one, and its value should normally stay stable.
Code Example
import jakarta.persistence.*;
@Entity
@Table(name = "customers")
public class Customer {
@Id // Marks this as the primary key
@GeneratedValue(strategy = GenerationType.IDENTITY) // Auto-increment
private Long id;
@Column(nullable = false, unique = true)
private String email;
@Column(nullable = false)
private String name;
// Composite key example in a junction table
}
@Entity
@Table(name = "order_items")
public class OrderItem {
@EmbeddedId // Uses both columns together as primary key
private OrderItemId id;
private Integer quantity;
private Double price;
}
Common Mistakes & Pitfalls
- Confusing a multi-column key with several keys: SQL allows one primary-key constraint, and that constraint may contain several columns.
- Using unstable contact data as identity: changing an email key also requires a policy for every referencing row.
- Forgetting the JPA identity requirement: a persistent entity needs an identifier mapping; use
@Id,@EmbeddedId, or a valid@IdClassmapping. - Treating the primary key as immutable automatically: SQL can allow an update unless permissions, application rules, or referential actions prevent it.
Check your understanding
Answer these without looking back at the article.
- What is the difference between a natural key and a surrogate key?
- Can a primary key span multiple columns?
- What is a composite primary key?
Looking for a structured roadmap?
Every module on this page is also part of the full Java backend interview track.