Tutorial Gateway

  • C
  • C#
  • Python
  • SQL
  • Java
  • JS
  • BI Tools
    • Informatica
    • Talend
    • Tableau
    • Power BI
    • SSIS
    • SSRS
    • SSAS
    • MDX
    • R Tutorial
    • Alteryx
    • QlikView
  • More
    • C Programs
    • C++ Programs
    • Go Programs
    • Python Programs
    • Java Programs
  • MySQL

SQL Foreign Key

SQL Foreign Key constraint is used to implement the relationship between SQL tables. To normalize the data, we split the tables using this SQL Server Foreign key relation. While splitting the data, we need a reference, and we call it as a foreign key relationship. The list of points you should remember before going to the example of Foreign Key in SQL Server.

  • You can link a SQL Server Foreign key column with a Primary Key constraint in another column, or a Unique Constraint column in another column.
  • Values you enter in the Foreign key column should match with the referenced column. Otherwise, SQL Server will throw an error.
  • You can define the SQL Server foreign key relationship with tables that are present within the same database and same server. You can use Triggers to provide cross referential integrity.
  • SQL allows you to define the foreign key relationship with another column present within the same table. This type of relationship is self-reference.
  • You can’t delete a table that has the foreign key relationship

For example, the Employee table has Employee ID, and Orders table has Orders information along with Emp ID. Remember, this Emp ID holds a Foreign Key relationship with the Employee ID column in the Employee table. For this SQL foreign key demonstration, we are using the Department table.

SQL Foreign Key 1

Create SQL Foreign Key

We can create a SQL Server Foreign key using the Transact SQL query, and the SQL Management Studio.

Create SQL Foreign Key using T-SQL

How to create a Foreign Key in SQL server using Transact SQL statement?. Here, we will create a Foreign key that will connect with the tblDepartment at the creation of a table.

-- Creating SQL Server Foreign Key
USE [SQLTEST]
GO

CREATE TABLE [dbo].[tblEmployee](
	[EmpID] [int] IDENTITY(1,1) NOT NULL PRIMARY KEY,
	[FirstName] [nvarchar](255) NULL,
	[LastName] [nvarchar](255) NULL,
	[Education] [nvarchar](255) NULL,
	[YearlyIncome] [float] NULL,
	[Sales] [float] NULL,
	[DeptID] [int] NULL,
	CONSTRAINT [FK_tblDepartment_tblEmployee_DeptID] FOREIGN KEY([DeptID])
		REFERENCES [dbo].[tblDepartment] ([ID])
) 
GO

We added the CONSTRAINT statement at the end of the table creation. CONSTRAINT Constraint_Name FOREIGN KEY (Column_Name of tblEmployee) REFERENCES PrimaryKey_Table (Key Column). Refer to Create Table, Primary Key, Unique Constraint, Triggers, and referential integrity in SQL Server.

SQL Foreign Key 2

Let me use the SP_HELP procedure to check the table definition and the constraints

SQL Foreign Key 3

See our newly created foreign key. You can also use the Object Explorer to achieve the same. To do so, Expand the tblEMployee, and expand Keys folder

SQL Foreign Key 4

Create SQL Foreign Key on Existing table

In this example, we show you the steps to add Foreign Key in SQL Server on an existing table. For this, we are going to create a new table.

-- Sql Server Foreign key example
USE [SQLTEST]
GO

CREATE TABLE [dbo].[tblEmployee](
	[EmpID] [int] IDENTITY(1,1) NOT NULL PRIMARY KEY,
	[FirstName] [nvarchar](255) NULL,
	[LastName] [nvarchar](255) NULL,
	[Education] [nvarchar](255) NULL,
	[YearlyIncome] [float] NULL,
	[Sales] [float] NULL,
	[DeptID] [int] NULL
) 
GO
SQL Foreign Key 5

Now let me add the Foreign key constraint. Here, we use the Alter Table to alter the table content, and then used the ADD Constraint statement to add the Foreign key constraint.

USE [SQLTEST]
GO
ALTER TABLE [dbo].[tblEmployee]  
ADD CONSTRAINT [FK_tblDepartment_tblEmployee_DeptID] FOREIGN KEY([DeptID])
			REFERENCES [dbo].[tblDepartment] ([ID])
SQL Foreign Key 6

Create Foreign Key using SSMS

In this example, we will show you how to create a Foreign Key in SQL Server using the SQL Server Management Studio. To do so, please go to the Object Explorer. Next, please Expand the Database folder, and select the table on which you want to create a Foreign key. Next, Right-click on it will open the context menu. Please choose the Design option.

SQL Foreign Key 11

It will open the corresponding table in design mode. Right-click on the DeptID column and select the Relationships option.

SQL Foreign Key 12

As you can see, there are no existing relationships. Please click on the Add button to add a new relation.

SQL Foreign Key 13

Once you select the Add option, SSMS will create a Foreign key for you.

SQL Foreign Key 14

Next, click on the Browse button beside the Tables and Columns Specification option. This property is used to specify the relation between the two tables.

SQL Foreign Key 15

We selected the Primary Key table as the tblDepartment, and Column as ID.

SQL Foreign Key 16

Next, we selected the Foreign key table as tblEmployee, and key column as the Dept ID

SQL Foreign Key 17

Modify Foreign Key

To modify SQL Server foreign key, go to the Database folder and select the table on which your Foreign key holds, then go to the Keys folder. Next, Right-click on the key name and select the Modify option

SQL Foreign Key 19

Clicking the Modify option will open the corresponding table in design mode, along with the Foreign Key Relationships window.

SQL Foreign Key 20

Delete Foreign Key using Query

Remember, You can’t alter the foreign constraint using the query. To modify the existing foreign key, you have to drop (or delete) and recreate it. Please use the DROP Constraint statement along with the ALTER TABLE Statement to delete or drop Foreign key in Sql Server

USE [SQLTEST]
GO
ALTER TABLE [dbo].[tblEmployee]  
DROP CONSTRAINT [FK_tblDepartment_tblEmployee_DeptID]
SQL Foreign Key 7

Delete Foreign Key Constraint using SSMS

Expand the Database folder, and choose the table on which your Foreign key holds, then go to the Keys folder. Next, Right-click on the key name and select the Delete option

SQL Foreign Key 8

Once you select the Delete option, Delete Object window will open. Click OK to delete the foreign key constraint.

SQL Foreign Key 9

You can see that there is no Foreign Key in the Object explorer

SQL Foreign Key 10

Delete Foreign Key Constraint using SSMS 2

To delete SQL foreign key, Within the object explorer, Expand the Database folder and Right-click on the table name, and click the Design option. Next, select the Relationships option to open this window. Now, Please select the Foreign Key, and click on the Delete button.

SQL Foreign Key 18

Filed Under: SQL

  • Install SQL Server
  • Install SQL Management Studio
  • Uninstall Management Studio
  • Install AdventureWorks Database
  • SQL Management Studio Intro
  • Connect SQL with sqlcmd utility
  • SQL Attach Database
  • SQL Detach Database
  • SQL Restore Database
  • Restore Database using BAK
  • SQL Rename Database with Files
  • Get SQL Database Names
  • SQL Create Table
  • SQL Rename Table
  • SQL Alter Table
  • SQL Add Column
  • SQL Rename Column
  • Get SQL Table Names in a DB
  • Find SQL Table Dependencies
  • Rename SQL Table & Column
  • SQL Global & Local Temp Table
  • SQL Table Variable
  • SQL Derived Table
  • SQL DATALENGTH
  • SQL Data Types
  • DML, DDL, DCL & TCL Cmds
  • SQL Query Builder
  • SQL ALIAS
  • SQL SELECT Statement
  • SQL SELECT DISTINCT
  • SQL SELECT INTO Statement
  • SQL INSERT Statement
  • SQL INSERT INTO SELECT
  • SQL BULK INSERT or BCP
  • SQL UPDATE Statement
  • SQL UPDATE from SELECT
  • SQL DELETE Statement
  • SQL TRUNCATE Table
  • SQL CASE Statement
  • SQL MERGE Statement
  • SQL Subquery
  • SQL CTE
  • SQL PIVOT
  • SQL UNPIVOT
  • SQL Clauses Examples
  • SQL TOP Clause
  • SQL WHERE Clause
  • SQL ORDER BY Clause
  • SQL GROUP BY Clause
  • SQL HAVING Clause
  • SQL Primary Key
  • SQL Foreign Key
  • SQL Referential Integrity
  • SQL Check Constraint
  • SQL Unique Constraint
  • SQL Default Constraint
  • SQL Clustered Index
  • SQL Non Clustered Index
  • SQL Filtered Indexes
  • SQL COALESCE Function
  • SQL IS NOT NULL
  • SQL IS NULL Function
  • SQL ISNULL
  • SQL JOINS
  • SQL CROSS JOIN
  • SQL FULL JOIN
  • SQL SELF JOIN
  • SQL Outer Joins
  • SQL Cross Join Vs Inner Join
  • SQL LEFT JOIN
  • SQL RIGHT JOIN
  • SQL AND & OR Operators
  • SQL Arithmetic Operators
  • SQL BETWEEN Operator
  • SQL Comparison Operators
  • SQL LIKE
  • SQL EXCEPT
  • SQL EXISTS Operator
  • SQL NOT EXISTS Operator
  • SQL INTERSECT
  • SQL IN Operator
  • SQL NOT IN Operator
  • SQL UNION
  • SQL UNION ALL
  • SQL IF ELSE
  • SQL ELSE IF
  • SQL WHILE LOOP
  • SQL Nested While Loop
  • SQL BREAK Statement
  • SQL CONTINUE Statement
  • SQL GOTO Statement
  • SQL IIF Function
  • SQL CHOOSE Function
  • SQL Change Data Capture
  • SQL Table Partitioning
  • SQL Table Partition using SSMS
  • SQL TRY CATCH
  • SQL VIEWS
  • SQL User Defined Functions
  • SQL Alter User Defined Functions
  • SQL Stored Procedure Intro
  • Useful System Stored Procedures
  • SQL SELECT Stored Procedure
  • SQL INSERT Stored Procedure
  • SQL UPDATE Stored Procedure
  • Stored Procedure Return Values
  • Stored Procedure Output Params
  • Stored Procedure Input Params
  • Insert SP result into Temp Table
  • SQL Triggers Introduction
  • SQL AFTER INSERT Triggers
  • SQL AFTER UPDATE Triggers
  • SQL AFTER DELETE Triggers
  • SQL INSTEAD OF INSERT
  • SQL INSTEAD OF UPDATE
  • SQL INSTEAD OF DELETE
  • SQL STATIC CURSOR
  • SQL DYNAMIC CURSOR
  • SQL FORWARD_ONLY Cursor
  • SQL FAST_FORWARD CURSOR
  • SQL KEYSET CURSOR
  • SQL TRANSACTIONS
  • SQL Nested Transactions
  • SQL ACID Properties
  • Create SQL Windows Login
  • Create SQL Server Login
  • SQL Server Login Error
  • Create SQL Server Roles
  • SQL Maintenance Plan
  • Backup SQL Database
  • SQL Ranking Functions Intro
  • SQL RANK Function
  • SQL PERCENT_RANK Function
  • SQL DENSE_RANK Function
  • SQL NTILE Function
  • SQL ROW_NUMBER
  • SQL Aggregate Functions
  • SQL Date Functions
  • SQL Mathematical Functions
  • SQL String Functions
  • SQL CAST Function
  • SQL TRY CAST
  • SQL CONVERT
  • SQL TRY CONVERT
  • SQL PARSE Function
  • SQL TRY_PARSE Function
  • SQL Calculate Running Total
  • SQL Find Nth Highest Salary
  • SQL Reverse String
  • SQL FOR XML PATH
  • SQL FOR XML AUTO
  • SQL FOR XML RAW

Copyright © 2021· All Rights Reserved by Suresh.
About | Contact | Privacy Policy