Composite Key in SQL
? Composite Key in SQL
A Composite Key is a primary key that consists of two or more columns combined to uniquely identify each row in a table.
? Why Use a Composite Key?
When a single column cannot uniquely identify a record.
To enforce uniqueness based on the combination of multiple columns.
? How to Define a Composite Key
1. During Table Creation
CREATE TABLE orders ( order_id INT, product_id INT, quantity INT, PRIMARY KEY (order_id, product_id));Here, the combination of
order_idandproduct_iduniquely identifies each row.
2. On an Existing Table
ALTER TABLE ordersADD CONSTRAINT pk_orders PRIMARY KEY (order_id, product_id);? Example Use Case
In an order details table, an order can have multiple products.
Neither
order_idnorproduct_idalone is unique.The combination of
order_idandproduct_iduniquely identifies each record.
? Key Points
Composite keys enforce uniqueness on multiple columns.
They are commonly used in many-to-many relationship tables (junction tables).
All columns in the composite key together must be unique.
Want me to show how composite keys work with foreign keys or examples in specific databases?