- SQL Server
SQL Server create table with primary key and unique key constrain and explain step by step
how to prevent null and duplicate values in a table and the difference between primary key and unique key.
- A table contains only one primary key allowed in a single table.
- Primary key does not allow null and duplicate values.
- By Default Primary key creates a cluster Index
- A table can have one or more unique constrain key.
- Unique key allows null values, but only one null value is allowed in a column
- The Unique key column does not support duplicate values
- By default, unique key creates a non-cluster Index.
Step - 1 create a table with primary key and unique key constraints in SQL Server Management Studio, Below example, I've used a student table
create table student
stid int not null primary key,
email nvarchar(150) unique,
phone int unique
Notice in the student table there is one primary key for stid and two unique keys for email, phone
Step 2 - execute to create the student table
Now, let's insert some student details in the table, right click the table and select the "Edit Top 200 Rows" Once the table is open enter student details.And you can notice the results in the table below I have entered..
Primary key does not have duplicate and null values
Unique key does have null with no duplicate values in the column.