SQL PRIMARY KEY Constraint

SQL PRIMARY KEY Constraint is used to define a column or a set of columns as the primary key of a table. A primary key is used to uniquely identify each record in a table and also to enforce referential integrity which ensures that the relationships between tables are maintained.

A table can only have one primary key and it can be made up of one or multiple columns. The primary key column must contain unique and non-null values, as it is used to identify each record in the table.

Here is an example of how to use SQL PRIMARY KEY Constraint while creating a table:

1CREATE TABLE Orders ( 2 OrderID int NOT NULL, 3 CustomerID int NOT NULL, 4 OrderDate date NOT NULL, 5 PRIMARY KEY (OrderID) 6);

In this example, the OrderID column is defined as the primary key for the Orders table. The NOT NULL constraint is used to ensure that each record has a value for the OrderID column.

Add PRIMARY KEY using ALTER statement

You can also use the ALTER TABLE statement to add or modify a PRIMARY KEY constraint on an existing table.

Here is an example of how to add a primary key to an existing table using the ALTER TABLE statement:

1ALTER TABLE Orders 2ADD PRIMARY KEY (OrderID);

In this example, a primary key is added to the Orders table using the OrderID column.

DROP PRIMARY KEY using ALTER statement

If you want to modify an existing primary key, you can drop the current primary key and create a new one. Here is an example of how to modify a primary key:

1ALTER TABLE Orders 2DROP PRIMARY KEY, 3ADD PRIMARY KEY (CustomerID);

In this example, the primary key is first dropped from the Orders table and then a new primary key is added using the CustomerID column.