Defining primary and foreign keys
A very important concept of relational databases is the use of primary and foreign keys. In this exercise, you will define a two new tables. A table Person
, with a PRIMARY KEY
and another table, History
, with a PRIMARY KEY
and a FOREIGN KEY
referencing the Person
table.
This exercise is part of the course
Hierarchical and Recursive Queries in SQL Server
Exercise instructions
- Define the primary key
PersonID
forPerson
of typeINT
. - Define the primary key
OrderID
forHistory
. - Define the foreign key
PersonID
referencing the primary key ofPerson
.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
CREATE TABLE Person (
-- Define the primary key for Person of type INT
___ ___ NOT NULL ___ ___,
Firstname VARCHAR(255) NOT NULL,
Lastname VARCHAR(255) NOT NULL,
);
CREATE TABLE History (
-- Define the primary key for History
OrderID INT ___ ___ ___ ___,
Item VARCHAR(255) NOT NULL,
Price INT NOT NULL,
-- Define the foreign key for History
PersonID INT ___ ___ REFERENCES Person(___)
);
SELECT *
FROM History;