What is fk in sql

Last updated: April 1, 2026

Quick Answer: FK stands for Foreign Key in SQL, a constraint that establishes a relationship between two tables by linking the primary key of one table to a column in another table.

Key Facts

What is a Foreign Key?

A Foreign Key (FK) is a database constraint that creates a link between two tables. It references the primary key of another table, establishing a parent-child relationship. This ensures that data in one table matches with data in another table, maintaining database integrity.

How Foreign Keys Work

When you define a Foreign Key on a column, the database enforces that every value in that column must either be NULL or match an existing primary key value in the referenced table. For example, if a "Orders" table has a Foreign Key referencing the "Customers" table's primary key, every order must be linked to a valid customer.

Benefits of Using Foreign Keys

Foreign Key Constraints

Foreign Keys support several constraint actions: RESTRICT prevents deletion of referenced rows, CASCADE automatically deletes child rows, SET NULL sets the foreign key to NULL when the parent is deleted, and NO ACTION is similar to RESTRICT but checked at transaction end. These actions determine how the database handles changes to parent records.

Creating Foreign Keys in SQL

You define a Foreign Key using the ALTER TABLE or CREATE TABLE statement. The syntax typically includes FOREIGN KEY (column_name) REFERENCES parent_table(primary_key). Most modern databases support Foreign Keys, including MySQL, PostgreSQL, SQL Server, and Oracle, making them a standard feature for maintaining database integrity.

Related Questions

What is the difference between primary key and foreign key?

A primary key uniquely identifies records within a table and cannot be NULL, while a foreign key references another table's primary key to create relationships. Primary keys enforce uniqueness; foreign keys enforce referential integrity.

What does ON DELETE CASCADE do?

ON DELETE CASCADE automatically deletes all child records when their parent record is deleted. This maintains referential integrity by ensuring no orphaned child records remain in the database.

Can a foreign key be NULL?

Yes, a foreign key column can be NULL unless explicitly defined as NOT NULL. A NULL foreign key means the record has no relationship to a parent record, which is valid in most database designs.

Sources

  1. Wikipedia - Foreign KeyCC-BY-SA-4.0
  2. PostgreSQL Documentation - ConstraintsCC-BY-SA-3.0