Foreign Key T-SQL

Add Constraint Foreign Key Example

To Create a foreign key in an existing table, use the command alter table with add constraint.

Employees table

USE tempdb;
GO
CREATE TABLE dbo.EMPLOYEES(
ID INT NULL,
NAME VARCHAR (250) NULL,
JOB VARCHAR (30) NULL,
DEPT_ID INT NULL );
GO

Departments table

USE tempdb;
GO
CREATE TABLE dbo.departments(
id int NOT NULL,
name varchar(250) );
GO

Create Constraint Foreign Key

USE tempdb;
GO
ALTER TABLE dbo.EMPLOYEES
ADD CONSTRAINT FK_DEPT_ID FOREIGN KEY(DEPT_ID)
REFERENCES dbo.DEPARTMENTS(ID);
GO