Adding Primary Key to Table in SQL Server

Hello to everyone,

In this article, I will provide information on how to add a primary key to the table in SQL Server.

In SQL Server, primary key fields are mostly used in tables. You can also do this using the Designer side. I will do this using code.

You can do this easily using the code below.

--Create a sample table

CREATE TABLE ExampleTableSample(
ID int not null ,
Name nvarchar(20)
)

--Adding a Primary Key to the Table

ALTER TABLE ExampleTableSample
ADD CONSTRAINT Example_PK PRIMARY KEY (ID);

The point to note here is that the field with the primary key is not NULL. Otherwise, you will get an error.

When you run the code, you will get a result like the one below.

Adding Primary Key to Table in SQL Server

As you can see, a primary key field has been added to the table.

Good luck to everyone in business and life.

144 Views

Yavuz Selim Kart

I try to explain what I know in software and database. I am still improving myself by doing research on many programming languages. Apart from these, I am also interested in Graphic Design and Wordpress. I also have knowledge about SEO and Social media management. In short, I am a determined person who likes to work hard.

You may also like...

Don`t copy text!