Last Updated : 23 Jul, 2025
A composite key is a primary key that is made up of more than one column to uniquely identify records in a table. Unlike a single-column primary key, a composite key combines two or more columns to ensure uniqueness. While any of the individual columns in a composite key might not be unique on their own, together they form a unique combination that can uniquely identify each row in the table.
Key Points to Remember:
Creating a database:
CREATE School;
Using database:
USE School;
Creating a table with a composite key:
CREATE TABLE student (rollNumber INT, name VARCHAR(30), class VARCHAR(30), section VARCHAR(1), mobile VARCHAR(10), PRIMARY KEY (rollNumber, mobile));
In this example, we have made the composite key as the combination of two columns i.e. rollNumber and mobile because all the rows of the table student can be uniquely identified by this composite key.
Inserting records in the table:
INSERT INTO student (rollNumber, name, class, section, mobile) VALUES (1, "AMAN","FOURTH", "B", "9988774455"); INSERT INTO student (rollNumber, name, class, section, mobile) VALUES (2, "JOHN","FIRST", "A", "9988112233"); INSERT INTO student (rollNumber, name, class, section, mobile) VALUES (3, "TOM","FOURTH", "B", "9988777755"); INSERT INTO student (rollNumber, name, class, section, mobile) VALUES (4, "RICHARD","SECOND", "C", "9955663322");
Querying the records:
SELECT * FROM student;
OUTPUT:
When to Use a Composite Key?A composite key is useful in situations where:
A composite key is a powerful tool in SQL, allowing you to create unique constraints across multiple columns. This can be especially helpful in situations where individual columns do not provide sufficient uniqueness. By combining multiple attributes into one primary key, you can ensure that each row in a table is uniquely identifiable.
This key is typically used when there's a natural relationship between the columns, and it’s often employed in cases where the table contains many-to-many relationships, requiring the combination of columns to uniquely identify records.
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4