📅  最后修改于: 2023-12-03 15:35:04.243000             🧑  作者: Mango
In SQL, a composite key is a combination of two or more columns in a table that together uniquely identify a row. It is also referred to as a composite primary key. The use of a composite key is important in database design as it ensures the uniqueness of the data and can increase the performance of queries.
To create a composite key, you need to specify multiple columns when creating or altering a table. For example, let's say we have a table called Employees
with columns ID
, FirstName
, LastName
, and Department
. We want to use the combination of ID
and Department
as the composite key.
CREATE TABLE Employees (
ID INT,
FirstName VARCHAR(50),
LastName VARCHAR(50),
Department VARCHAR(50),
PRIMARY KEY (ID, Department)
);
In the above example, we have specified the composite key by adding the PRIMARY KEY
constraint on two columns ID
and Department
.
When querying a table with a composite key, you need to include all columns in the WHERE clause. For example, to retrieve a row with ID = 1
and Department = 'Sales'
from the Employees
table, the query would look like this:
SELECT * FROM Employees WHERE ID = 1 AND Department = 'Sales';
Using a composite key in SQL has several benefits, such as:
Overall, using a composite key in SQL can improve database performance and ensure data integrity. It involves specifying multiple columns as the primary key when creating or altering a table. When querying with a composite key, all key columns must be included in the WHERE clause.