Primary key, Foreign Key and Default constraint are the 3 main constraints that need to be considered while creating tables or even after that. It seems very easy to apply these constraints but still we have some confusions and problems while implementing it. So I tried to write about these constraints that can be created or added at different levels and in different ways or methods.
Primary Key Constraint: Primary Keys constraints prevents duplicate values for columns and provides unique identifier to each column, as well it creates clustered index on the columns.
1)     Create Table Statement to create Primary Key
a.      Column Level
USE AdventureWorks2008 GO CREATE TABLE Products ( ProductID INT CONSTRAINT pk_products_pid PRIMARY KEY, ProductName VARCHAR(25) ); GO
b.     Table Level
CREATE TABLE Products ( ProductID INT, ProductName VARCHAR(25) CONSTRAINT pk_products_pid PRIMARY KEY(ProductID) ); GO
2)Â Â Â Â Â Alter Table Statement to create Primary Key
ALTER TABLE Products ADD CONSTRAINT pk_products_pid PRIMARY KEY(ProductID) GO
3)Â Â Â Â Â Alter Statement to Drop Primary key
ALTER TABLE Products DROP CONSTRAINT pk_products_pid; GO
Foreign Key Constraint: When a FOREIGN KEY constraint is added to an existing column or columns in the table SQL Server, by default checks the existing data in the columns to ensure that all values, except NULL, exist in the column(s) of the referenced PRIMARY KEY or UNIQUE constraint.
1)     Create Table Statement to create Foreign Key
a.      Column Level
USE AdventureWorks2008 GO CREATE TABLE ProductSales ( SalesID INT CONSTRAINT pk_productSales_sid PRIMARY KEY, ProductID INT CONSTRAINT fk_productSales_pid FOREIGN KEY REFERENCES Products(ProductID), SalesPerson VARCHAR(25) ); GO
b.     Table Level
CREATE TABLE ProductSales ( SalesID INT, ProductID INT, SalesPerson VARCHAR(25) CONSTRAINT pk_productSales_sid PRIMARY KEY(SalesID), CONSTRAINT fk_productSales_pid FOREIGN KEY(ProductID)REFERENCES Products(ProductID) ); GO
1)Â Â Â Â Â Alter Table Statement to create Foreign Key
ALTER TABLE ProductSales ADD CONSTRAINT fk_productSales_pid FOREIGN KEY(ProductID)REFERENCES Products(ProductID) GO
2)Â Â Â Â Â Alter Table Statement to Drop Foreign Key
ALTER TABLE ProductSales DROP CONSTRAINT fk_productSales_pid; GO
Default Constraint: Default constraint when created on some column will have the default data which is given in the constraint when no records or data is inserted in that column.
1)Â Â Â Â Â Create Table Statement to create Default Constraint
a.      Column Level
USE AdventureWorks2008 GO CREATE TABLE Customer ( CustomerID INT CONSTRAINT pk_customer_cid PRIMARY KEY, CustomerName VARCHAR(30), CustomerAddress VARCHAR(50) CONSTRAINT df_customer_Add DEFAULT 'UNKNOWN' ); GO
b.     Table Level : Not applicable for Default Constraint
2)Â Â Â Â Â Alter Table Statement to Add Default Constraint
ALTER TABLE Customer ADD CONSTRAINT df_customer_Add DEFAULT 'UNKNOWN' FOR CustomerAddress GO
3)Â Â Â Â Â Alter Table to Drop Default Constraint
ALTER TABLE Customer DROP CONSTRAINT df_customer_Add GO
Reference : Pinal Dave (https://blog.sqlauthority.com)
131 Comments. Leave new
I’ve a problem in sql server just could you tel me ?
there are four tables in my database and there are two primary keys in two different table I need to filter data s by using those primary keys when I prepare reports, but in the beginning I’ve given only 1 primary key as foreign key to other tables
My question is can I insert in this stage the other particular primary key as foreign key to other tables?
its very argent ! I know you can help me
Hello Mr. Stephen,
You can insert the other primary key as foreign key to other tables provided you have the data in the tables that do not conflict with the combination keys (existing primary key and the new foreign key). In that case, you will have to make the corrections in the data already existing in the table and then insert the keys.
Also, after making changes in the design of the table, do not forget to refresh the data in reports.
Kind Regards,
Pinal Dave
sir
please tell me how can i create table in sql server.what process of start sql and then reached the table sheet.and also create contrant primary key foreign key .
Read about “CREATE TABLE” in SQL Server help file
first you have to create one table then –.> go to stored procedure –>
and write code like a
create procedure [procedure_name]
(
declare variables
[while u declare a variable start with ‘ @ ‘ and end with ,]
example
@name nvarchar(50)
Hello Mr.Pinal Dave,
I read your post regarding Constraints in Sql.Its very useful & Easy to understand.
As well,Short and Sweet.
Thanks a lot..
Regards
Anbu with Love
I am a newbee to SQL and I am working on a metrics table. I have the SQL 2008 Express on my computer.
The name of the database is PlantMetrics and the name of the table is dbo.PerformanceIndexes.
I have three columns containing:
PlantName
Month
Year
The combination of values in these three columns is unique. When I post the metrics for each plant for each month, the values of PlantName, Month and Year will repeat from record to record.
Can I denote these three columns as primary keys? If so how?
Or do I leave the table without primary key constraint?
I want to add other tables to the database with details of other characteristics for the plants and relate them to this table.
The other tables will have unique values for the PlantName etc.
Thanx for your Example Posts.They are really really helpful
hi sir,
i am vinoth we are using sql server 2008 i want to display the content table for daily updates….
hi sir,
i am vinoth. we are using for sql server 2008. i want display
recorded data… for example when i entered in office using
my id card that time..the product software recorded…
already recorded and new record data i want to display
screen with using sql server 2008.
which command we have to use…. please give me solution..
Thanks & Regards,
vinoth.A
If you have datetime column with default getdate(), you can find it
can you please tell me about logins and users n sql server?
Hi Pinal Sir,
Thanks for your tutorial about adding primary key and foreign key using alter statement at column level and table level.
Anshu
Hi Pinal Sir,
In the scenario of foreign key and primary key both are providing the same feature but what is the actual difference between column level and table level ?
CREATE table Customers
(CustomersID char(5) not null,
Address varchar (60) null,
City char(15) null,
Phone char (24)null,
Fax char (24) null,
constraint pk_Customers primary key (CustomerID)
)
CREATE table Orders
(OrdersID int,
CustomerID char not null,
Orderdate datetime null,
Shippeddate datetime null,
Quantity int null,
constraint pk_Orders primary key (OrdersID, CustomerID)
)
i am now satisfy with your answer
thanks
Hello
Pinal
Your posts are really very helpful
thank you
Hi Pinal Sir,
I hava a problem in creating foreign key in my sql table.im using sql 2008.
Can i set two foreign keys in two child tables with references to one unique key in main table .
pleas help me.
try to chage your main table unique key bcoz unique key access from the null values so try to use primary key then u il set the foreign key ur table
i am now satisfy with ur answer
thanks
dear sir,
i have a table called student_ id with 3 column id(pkey),name and course.
i wants to access id (start with 3 and end with 8,means 5 values)
hw can this is possible with asp.net application
can anyone help me!!!
when ever i create identity primary key tat error showing all the times
“Must declare the scalar variable “@”ID”
HAI,
I want learn SQL more.Is any way to understand SQL easely.
REGARDS
Dinesh
Can’t we create a default constraint at table level ???
Hi Mr. Pinal,
One table having one cluster Index in the case of one primary key. If more than one primary keys are there in a table, then how many clustered Indexes are created for table?
Please reply me……
Thanks & Regards
Madhu….
Note that there cannot be more than one primary key in a table