Introduction
In this article, we will learn how to add primary key to existing tables in SQL Server. Here we will use SQL Server as our database. SQL Server is a relational database management system. A primary key constraint creates a unique identifier for each row in a table. This is usually done using an auto-incrementing identity column.
ALTER TABLE SQL statement can be used to alter a table that includes adding a primary key to an existing table. In this example, we are going to create a database table called Books without a primary key and then we will add a primary key to the table using the ALTER TABLE SQL statement.
What is a primary key
A primary key is a unique identifier that uniquely identifies each row in a table.
A primary key consists of one or more columns and must be unique for each row in the table.
The column(s) that make up the primary key cannot contain null values, but all other columns can contain null values.
Why do we need a primary key
- A primary key is one or more columns that uniquely identify each table record. Because the values in a primary key are unique, you can use it to identify and retrieve records faster than when using other column(s). A table with a primary key allows you to maintain data integrity by ensuring that the data in your tables do not include duplicate records.
- A primary key also helps to improve performance as it provides an easy way for SQL Server to locate specific records when it processes queries. For example, if you want information about a particular order item, SQL Server will have no problem finding this data because of its unique identifier.
- A primary key constraint is a unique identifier that's used to identify each row in a table. It also ensures that no other row in the table has the same primary key value. With a primary key constraint, you can't delete or update rows unless there are no remaining rows with duplicate values for the column being modified.
- A good way to think about this is like when you go through security at an airport and they ask you which bag belongs to whom—the ID number acts as a unique identifier so they know which bag belongs to which traveler.
- Primary keys are used for two main purposes: data integrity and referential integrity (RI). Data integrity means that your data will be accurate because it can't be changed without affecting something else; RI ensures that related tables have matching field names so that if one thing changes, everything else associated with it changes too.





Bobby BrownPosted Jan 5, 2024, 11:42 AM
Thanks for the helpful tips! For those interested in this topic, I suggest exploring this article (https://blog.devart.com/sql-server-primary-key.html), which also describes adding a primary key to an existing table in SQL.