100 Days of SQL

sql

Day 37 – SQL PRIMARY KEY Constraint

In SQL, the PRIMARY KEY constraint is used to specify a column or a set of columns that uniquely identify each row in a table. The primary key constraint ensures that the values in the specified column(s) are unique and cannot be null.

A table can have only one primary key, and it can be defined at the time of creating the table or added later using the ALTER TABLE statement. When a primary key is defined on a column, the database automatically creates an index on that column for faster searching and sorting of data.

The syntax for defining a primary key constraint when creating a table is as follows:


CREATE TABLE table_name (
   column1 datatype PRIMARY KEY,
   column2 datatype,
   column3 datatype,
   .....
);

The syntax for adding a primary key constraint to an existing table is as follows:


ALTER TABLE table_name
ADD PRIMARY KEY (column1, column2, ...);

In the above syntax, column1, column2, etc. are the names of the columns that you want to include in the primary key.

It is important to choose the right column(s) to define as the primary key because the primary key will be used as a reference by other tables, and changing the primary key can have significant impacts on the database’s performance and data integrity.