Create table with primary key in sql server example

Create table with primary key in sql server example

In this blog i am going to explain about how to Create table with primary key in sql server example. You can check some of my previous sql server blog posts.

  1. SQLServer IDENTITY Column with text
  2. Sql Select statement with auto generated row id
  3. SQL Query to backup database in sql server
  4. Create or reset the identity value of a column in sql server
  5. Insert values into identity column in sql server



Implementation:

Now we will see the implementation of how to create table with primary key in sql server example. Before proceeding let me explain what is primary key. Primary key is a constraint used to uniquely identify each row in the table. By default whenever we create the primary key on a column of a table clustered index will be automatically created on that column.

Create Primary Key Using SQL Server Management Studio:

Open sql server choose and expand your database and right click on the tables and choose New Table option as shown in the below image.

Step 1 of Create table with primary key in sql server example

Now enter the column name and datatype as per your need and finally right click the column on which you want to create primary key. Choose Set Primay Key option. Then primary key will be generated on that column. Refer the below image.

Step 2 of Create table with primary key in sql server example

Create Primary Key Using Transact SQL:

Now let see how to create primary key using transact sql. For demonstrating i created a simple table called Customer. Below is the sql script.

Now here i want to make the CustomerId column as Primary Key. So i changed my script like below and executed.

So this script created CustomerId with primary key constraint. If you run the sp_help command on customer table you can see this.

Step 3 of Create table with primary key in sql server example

 

Conclusion:

Hope you learned how to create table with primary key in sql server with example. Do you like this tutorial? Help us to improve. Please post your comments and feedback below.

Leave a Reply

Your email address will not be published. Required fields are marked *