SQL Creating a table with a foreign key


Example

In this example we have an existing table, SuperHeros.

This table contains a primary key ID.

We will add a new table in order to store the powers of each super hero:

CREATE TABLE HeroPowers
(
    ID int NOT NULL PRIMARY KEY,
    Name nvarchar(MAX) NOT NULL,
    HeroId int REFERENCES SuperHeros(ID)
)

The column HeroId is a foreign key to the table SuperHeros.