Showing posts with label Primary Key. Show all posts
Showing posts with label Primary Key. Show all posts

Monday, 18 April 2016

How to add Primary key in the existing table in SQL server ?

Primary key is a kind of constraint in SQL server .To add the primary key in the existing table , you can do it in two ways.
  1. Using SQL Management Studio
  2. Using T-SQL Query
Using SQL Management Studio:

Step1:
Expand the database ,right click the required table and click the design option as shown below.



Step2:

Right click the required column and select the option as set the primary key as shown below.




Step3:

After clicking the option you can find the Key icon in the selected column as shown below.


Primary key is created successfully in StudentDetail table using SQL Management studio.

Using T-SQL Query:

Sunday, 20 September 2015

How to create the primary key in SQL server after table creation ?

If we forget to create the primary key while table creation,we  also have the option to add the primary key for the existing table.

We can add the primary for the existing table using ALTER TABLE keyword.

Syntax  :

ALTER TABLE [TABLE NAME] ADD CONSTRAINT [PRIMARY KEY NAME] PRIMARY KEY  ([COLUMN NAME] ASC)

Example :

ALTER TABLE Student ADD CONSTRAINT PK_Student PRIMARY KEY ([StudentID] ASC)


Explanation: 

PK_Student --> Refers to primary key name.
StudentID -- > Refers to the primary key column name.


Now the primary key is created successfully in the existing table using T-SQL query.


Saturday, 19 September 2015

What is primary key in a table and How to create it ?

Primary key is one of the constraints in SQL server which enforces the Unique value for each row in a table.

A table can have only one primary key.The column which act as a primary key will not allow null values.Usually the primary key columns are defined on identity columns.

Create Syntax : 

CREATE TABLE [TABLENAME]
(
    [COLUMNNAME] [DATETYPE] [CONSTRAINT],
    [COLUMNNAME1] [DATETYPE] [CONSTRAINT],
    .
    .
    .
    [COLUMNNAME(N)] [DATETYPE] [CONSTRAINT],
)

Example :

CREATE TABLE dbo.Department
(
    [ID] [INT] IDENTITY(1,1) NOT NULL PRIMARY KEY,
    [NAME] VARCHAR(10) NULL, 
    [AGE] [INT] NOT NULL
)

If we use the above method then the primary key will be created by the database engine.
If you want to create the primary key on user defined name ,then use the below method.

Example :

CREATE TABLE dbo.Department
(
    [ID] [INT] IDENTITY(1,1) NOT NULL ,
    [NAME] VARCHAR(10) NULL, 
    [AGE] [INT] NOT NULL,
    CONSTRAINT [PK_ID] PRIMARY KEY CLUSTERED ([ID]  ASC)    
)

Now the primary key will be created in the name of PK_ID.
Now we created the constraint in ASC order,so it will always order the data in ascending order.