SQL Primary Key

‮h‬ttps://www.theitroad.com

In SQL, a primary key is a column or set of columns that uniquely identifies each row in a table. The primary key constraint ensures that each value in the primary key column(s) is unique and not null.

Here is an example of how to create a primary key constraint on a table:

CREATE TABLE customers (
    customer_id INT PRIMARY KEY,
    customer_name VARCHAR(50),
    customer_email VARCHAR(50)
);

In this example, the customer_id column is designated as the primary key for the customers table. This means that each row in the table must have a unique value in the customer_id column. The primary key constraint can also be applied to multiple columns in a table, in which case the combination of values in the columns must be unique.

You can add a primary key constraint to an existing table using the ALTER TABLE command:

ALTER TABLE customers
ADD CONSTRAINT pk_customers PRIMARY KEY (customer_id);

In this example, we are adding a primary key constraint to the customer_id column of the customers table using the ALTER TABLE command.

The primary key is an important aspect of table design, as it ensures that each row in the table can be uniquely identified and linked to other tables using foreign key constraints. It also provides a fast way to access specific rows in the table, as the primary key column(s) are often indexed.