

It's also a big mistake not to have a primary key in the table in fact, it's a well-known mistake made by both beginner and experienced SQL programmers who are well documented by Bill Karwin in his excellent book, SQL Antipatterns: Avoiding the Pitfalls of Database Programming By Pragmatic Programmers.Ī programmer needs to identify the right columns and ensure a table has a primary key at the time of creation. I will share the T-SQL query with you to add the primary key into an existing table in SQL Server. It's not difficult to add the primary key into a new table, but if you have an existing table with data and you want to add the primary key, how would you do that? What SQL command will you use? This is what you will learn in this Microsoft SQL server tutorial.

Alternatively, you can also combine multiple columns to create composite primary keys, like you can combine firstname and lastname to create a primary key name, etc. If you don't have a column that can serve as the primary key, you can use identity columns for that purpose. Sometimes, this is due to lack of a column that is both NOT NULL and UNIQUE (constraint require to be a primary key), but other times purely due to lack of knowledge or lack of energy. Though it's an SQL and database best practice to always have a primary key in a table, you will often find tables that don't have a primary key. Since a primary key is nothing but a constraint, you can use the ALTER clause of SQL to add a primary key into the existing table.
