Foreign Key Constraint

SQL Foreign Key Constraint

A SQL Foreign Key constraint is a column or combination of columns that is used to create link between the data in two tables.
When a value other than NULL is entered into the column of a FOREIGN KEY constraint, the value must exist in the referenced column.
FOREIGN KEY constraints can reference only tables within the same database on the same server.

Example

CREATE TABLE Test1
(
ID INT PRIMARY KEY,
TITLE VARCHAR(250) NOT NULL,
);

CREATE TABLE Test2
(
ID INT PRIMARY KEY,
TITLE VARCHAR(250) NOT NULL,
CONSTRAINT FK_Test1 FOREIGN KEY (ID)     
    REFERENCES Test1 (ID)     
    ON DELETE CASCADE    
    ON UPDATE CASCADE   
);

CREATE TABLE Test3
(
ID INT PRIMARY KEY,
ID_TEST INT NOT NULL,
CONSTRAINT UK_IDTEST UNIQUE(ID_TEST) 
);

ALTER TABLE Test3    
ADD CONSTRAINT FK_Test13 FOREIGN KEY (ID_TEST)     
    REFERENCES Test1 (ID)       
;