Composite Key in SQL

A composite key, also known as a composite primary key, is a combination of two or more columns in a table that can be used to uniquely identify each row in the table. In SQL, a composite key is created by defining multiple columns as the primary key of a table, rather than just one column.

Here's an example of how to create a composite key in SQL:

CREATE TABLE users ( user_id INT NOT NULL, username VARCHAR(255) NOT NULL, password VARCHAR(255) NOT NULL, PRIMARY KEY (user_id, username) ); 

In this example, the user_id and username columns are both part of the composite primary key. This means that each combination of user_id and username must be unique within the users table.

Composite keys are often used when a single column cannot uniquely identify a row, or when multiple columns are required to uniquely identify a row. For example, a composite key might be used to ensure that each combination of a user's first_name and last_name is unique within a table of users.

Points to remember when creating composite key

Here are a few more things to keep in mind when working with composite keys in SQL:

  • Composite keys can be created using any number of columns, but typically they consist of two or three columns.
  • Each column in a composite key must have a unique value within the table.
  • Composite keys can be used as foreign keys in other tables, just like single-column keys.
  • Composite keys can be created using any data type, as long as the combination of values in the key is unique.
  • It is important to carefully consider the design of a composite key, as changing the key in the future can be difficult and may require updating other tables that depend on the key.

Here's an example of how to use a composite key as a foreign key:

CREATE TABLE orders ( order_id INT NOT NULL, user_id INT NOT NULL, product_id INT NOT NULL, quantity INT NOT NULL, PRIMARY KEY (order_id), FOREIGN KEY (user_id, product_id) REFERENCES users (user_id, product_id) ); 

In this example, the composite key consisting of the user_id and product_id columns is used as a foreign key in the orders table. This means that the combination of user_id and product_id values in the orders table must match a combination of user_id and product_id values in the users table