Composite Key in Database (original) (raw)

Last Updated : 23 Jul, 2025

A database is a structured collection of data organized and stored electronically in a computer system. It is designed to efficiently manage, retrieve, and manipulate large volumes of data according to specific requirements and criteria.

In a relational database, the key plays an important role. The key is used to identify a record or a tuple of the table uniquely. Keys are also used to establish and identify the relationships between the tables.

Types of Keys in Database

Composite Key

A composite key is a candidate key consisting of two or more attributes(table columns) that uniquely identify a record/tuple (table row) or a relation. A compound key is a composite key for which each attribute that makes up the key is a foreign key in its own right.

Examples

Consider we have a table _Orders with three attributes __Customer id, Product id, Quantity._The key

Fig.1 Orders table

Fig.1 Orders table

_Customer id needs to be entered every time the order is placed, hence _Customer id can repeat in the table and can not serve as a primary key. Also, _Product id and _Quantity cannot be chosen as primary key because multiple customers can buy same product and the same quantity. Here any of the three attributes can not be used as primary key, hence combination of these attributes need to be used.

For example, [Customer id + Product id] can be used to identify the records uniquely.

Fig. 2 Orders table

Fig. 2 Orders table

Syntax to Create Composite Key in mySQL

_CREATE TABLE Orders

_(

Customer_id INT,

Product_id INT,

Quantity INT,

PRIMARY KEY (Customer_id, Product_id)

_);

How to Choose Attributes for Composite Key?

Advantages of Composite Key

Disadvantages of Composite Key

Conclusion

Composite keys guarantee that every file has a unique identification, by ensuring that each record in the relational database has a clear distinction from any other record. This is true and these features can be considered both as a strength, comparing to regular text books and as a weakness, comparing to traditional text books, which are more convenient for maintenance and searching. Key composite can be used to increase data accuracy and retrieval efficiency by database systems with attention and contributed by the implementation in correct and proper ways.