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.
Latihan ini adalah bagian dari kursus
Hierarchical and Recursive Queries in SQL Server
Petunjuk latihan
- Define the primary key
PersonIDforPersonof typeINT. - Define the primary key
OrderIDforHistory. - Define the foreign key
PersonIDreferencing the primary key ofPerson.
Latihan interaktif praktis
Cobalah latihan ini dengan menyelesaikan kode contoh berikut.
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;