FOREIGN KEY
FOREIGN KEY is a keyword in SQL that denotes foreign key constraints in database management systems. It establishes a link between the data in two tables by connecting a key in one table with the primary key of another table. This link enforces referential integrity, ensuring that the relationship between the linked tables remains consistent.
Example
Output
Explanation
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.
Example
Output
Explanation
In the example above, a FOREIGN KEY
constraint is defined on the PersonID
column in the Orders
table. The PersonID
column in the Orders
table points to the PersonID
column in the Persons
table. This means that for every entry in the Orders
table, the value of PersonID
must match an existing value in the PersonID
column of the Persons
table. With this constraint, you ensure the referential integrity of your data in the PostgreSQL database.
Example
Output
Explanation
In the given example, a table named Orders
is created. The FOREIGN KEY
constraint is utilized on the CustomerID
column in the Orders
table, pointing to the CustomerID
in the Customers
table. This action ensures that every value in the Orders.CustomerID
column exists in the Customers.CustomerID
column, enforcing referential integrity in the database. The output message Command(s) completed successfully
indicates that the table was successfully created with the foreign key constraint.
Example
Output
Table ORDERS created.
Explanation
In this example, a database table named Orders
has been created. The FOREIGN KEY
constraint on the CustomerID
field ensures that every CustomerID
in the Orders
table matches a CustomerID
in the Customers
table. This prevents misspelled or nonexistent customer IDs from being added to the Orders
table.
Example
Output
Explanation
The FOREIGN KEY
keyword is used in SQLite (and other SQL databases) to ensure referential integrity of data within your database. In the code example, each book entry in the Books
table has an AuthorID
that must correspond to an existing AuthorID
in the Authors
table. This link between tables helps ensure that a book cannot be entered into the database without a referenced author.