In relational databases a key is a one-or-more-column constraint used to guarantee uniqueness or establish referential integrity. The most common types are:• Primary key – uniquely identifies each row in a table and cannot contain NULL values.• Foreign key – enforces a relationship between a column (or set of columns) in one table and the primary or unique key in another table.• Unique key – guarantees that all values in the constrained column(s) are distinct but can allow a single NULL depending on the dialect.• Composite key – any primary, unique, or foreign key that involves multiple columns.Keys improve query performance when the underlying database automatically creates an index, and they protect data integrity by rejecting duplicate or orphaned rows. When planning schemas choose stable, minimal columns for primary keys, prefer surrogate keys for large or frequently updated tables, and add explicit indexes to foreign keys if the dialect does not create them automatically. Dropping or altering keys on large tables can lock or block writes so perform such operations during maintenance windows.
PRIMARY KEY, FOREIGN KEY, UNIQUE, INDEX, CONSTRAINT, ON DELETE CASCADE
ANSI SQL-86
A primary key uniquely identifies each row and cannot contain NULL values. A unique key also guarantees uniqueness but may allow a single NULL depending on the database engine.
You can have only one primary key constraint per table, but it can consist of multiple columns (composite key).
Primary and unique keys are indexed automatically in most systems. Some engines do not auto-index foreign keys, so add an index manually for better join performance.
Composite keys can slow inserts and updates because all columns must be checked for uniqueness. Consider a surrogate primary key plus a separate unique constraint if write performance is critical.