Foreign Key
Allows you to point at another table’s index for fast referencing.
CREATE TABLE SchameName.TableName(
ColName1 smallint IDENTITY(1,1) NOT NULL PRIMARY KEY,
ColName2 VARCHAR(50) UNIQUE,
CONSTRAINT FK_ColNameId
FOREIGN KEY (ColName2)
REFERENCES SchemaName.OtherTable(ColName2) -- composite would be (ColName2, ColName3)
ON DELETE CASCADE -- or SET NULL / SET DEFAULT / NO ACTION (default)
ON UPDATE NO ACTION; -- CASCADE exists but use sparingly
)
ALTER TABLE SchemaName.TableName
ADD CONSTRAINT FK_ColNameId
FOREIGN KEY (ColNameId)