What is Primary Key Constraint and Unique Key Constraints?
What is Primary Key Constraint and Unique Key Constraints?
In SQL, both Primary Key and Unique Key constraints are used to ensure data uniqueness within a table, but they serve different purposes and have distinct characteristics.
A primary key is a column or a set of columns that uniquely identifies each row in a table. This constraint has several important characteristics:
Examples of SQL syntax for creating a primary key are as follows:
-- Creating a primary key on a single column during table creation
CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
PRIMARY KEY (ID)
);
-- Creating a composite primary key during table creation
CREATE TABLE Orders (
OrderID int NOT NULL,
ProductID int NOT NULL,
OrderDate date NOT NULL,
PRIMARY KEY (OrderID, ProductID)
);
A unique key constraint also ensures that all values in a column or a set of columns are unique across the database table. However, it differs from the primary key constraint in the following ways:
junior
Gợi ý câu hỏi phỏng vấn
Chưa có bình luận nào