FOREIGN KEY constraint in sql server


FOREIGN KEY- This constraint responsible for uniquely identified rows or records to another table.

Example-

Following table structure can clear your concept of foreign key constraints.

Product Table

CREATE TABLE PRODUCT
(
ID INT NOT NULL IDENTITY(1,1),
SKU VARCHAR(20) NOT NULL,
TITLE VARCHAR(200) NOT NULL,
PRICE MONEY NOT NULL,
DESCRIPTION VARCHAR(2000)  NULL,
DTCREATE DATETIME NULL
CONSTRAINT pk_ID PRIMARY KEY (ID)
)

Product Order Table

CREATE TABLE PRODUCT_IMAGE
(
ID INT NOT NULL IDENTITY(1,1),
PRODUCT_ID INT NOT NULL REFERENCES PRODUCT(ID),
IMGURL VARCHAR(200) NOT NULL ,
DTCREATE DATETIME
)

To create a foreign key constraint to existing table use following query.

ALTER TABLE PRODUCT_IMAGE ADD FOREIGN KEY (PRODUCT_IDREFERENCESPRODUCT(ID)

Related Posts

What is the Use of isNaN Function in JavaScript? A Comprehensive Explanation for Effective Input Validation

In the world of JavaScript, input validation is a critical aspect of ensuring that user-provided data is processed correctly. One indispensa...