Skip to content

FOREIGN KEY

CREATE TABLE Authors (
ID INT PRIMARY KEY,
Name VARCHAR(100)
);
CREATE TABLE Books (
ID INT PRIMARY KEY,
Title VARCHAR(100),
AuthorID INT,
FOREIGN KEY (AuthorID) REFERENCES Authors(ID)
);
Query OK, 0 rows affected (0.01 sec)
Query OK, 0 rows affected (0.02 sec)

This code excerpt creates two tables, Authors and Books. The Authors table has two columns: ID and Name. The Books table has three columns: ID, Title, and AuthorID. Here AuthorID is declared as a foreign key referencing ID field in the Authors table. This set up ensures each book is associated with an author from the Authors table.