SQL - Composite Key
In SQL Server, a composite key is a key that consists of two or more columns in a table. It is used to uniquely identify a row by combining the values of multiple columns. Each column within the composite key contributes to the uniqueness of the key when taken together as a whole.
The composite key ensures that the combination of values in the specified columns is unique within the table. This means that no two rows can have the same combination of values for all the columns in the composite key.
Let's illustrate the concept of a composite key with an example:
Suppose we have a table called "Orders" with the following columns: OrderID, CustomerID, and ProductID. We want to ensure that each order is uniquely identified by the combination of CustomerID and ProductID. In this case, we can create a composite key on the CustomerID and ProductID columns.
Here's an example of creating a table with a composite key in SQL Server:
CREATE TABLE Orders (
OrderID INT PRIMARY KEY,
CustomerID INT,
ProductID INT,
-- Creating a composite key on CustomerID and ProductID
CONSTRAINT PK_Orders PRIMARY KEY (CustomerID, ProductID)
);
In this example, we define a composite key constraint using the PRIMARY KEY keyword and specifying the CustomerID and ProductID columns within parentheses. This ensures that the combination of CustomerID and ProductID is unique for each row in the table.
Let's insert some sample data into the "Orders" table to see how the composite key works:
INSERT INTO Orders (OrderID, CustomerID, ProductID)
VALUES (1, 101, 201);
-- This insert will succeed since the combination (102, 201) is unique
INSERT INTO Orders (OrderID, CustomerID, ProductID)
VALUES (2, 102, 201);
-- This insert will fail since the combination (101, 201) already exists
INSERT INTO Orders (OrderID, CustomerID, ProductID)
VALUES (3, 101, 201);
In the above example, the first two inserts succeed because they have unique combinations of CustomerID and ProductID. However, the third insert fails because it violates the uniqueness constraint imposed by the composite key.
By using a composite key, we can ensure that each order in the "Orders" table is uniquely identified by the combination of CustomerID and ProductID, providing data integrity and preventing duplicate entries based on multiple columns.