codingstuff.io
ExploreTutorialsProblemsCS Subjects
Get Started
ExploreTutorialsProblemsCS Subjects
Get Started
codingstuff.io

Master the art of building software through interactive tutorials, real-world problems, and guided projects.

Pune, Maharashtra, India

codingstuffmail@gmail.com

Product

  • Explore
  • Tutorials
  • Problems
  • CS Subjects

Company

  • About
  • Contact
  • Privacy Policy
  • Terms & Conditions
  • Sitemap

© 2026 codingstuff.io. All rights reserved.

Built with ❤️ for developers everywhere

/
/
All Tutorials
🗄️

SQL & Databases

10 / 67 topics
6Creating a Database7Tables and Columns8Data Types9Primary Keys10Foreign Keys11Constraints
Tutorials/SQL & Databases/Foreign Keys
🗄️SQL & Databases

Foreign Keys

Updated 2026-05-15
10 min read

Foreign Keys

Introduction

In the world of relational databases, foreign keys are a fundamental concept that allows us to establish and maintain relationships between tables. By defining foreign keys, we ensure data integrity and consistency across our database schema. This tutorial will guide you through understanding what foreign keys are, how they work, and how to implement them in SQL.

Concept

What is a Foreign Key?

A foreign key is a column (or a set of columns) in one table that uniquely identifies a row of another table or the same table. It serves as a link between two tables based on a related column between them. The purpose of a foreign key is to ensure referential integrity, meaning that the data in the foreign key column must match the values in the primary key column of the referenced table.

Key Points

  • Primary Key: A unique identifier for each row in a table.
  • Foreign Key: A field (or collection of fields) in one table that uniquely identifies a row of another table.
  • Referential Integrity: Ensures that relationships between tables remain consistent and accurate.

Examples

Let's illustrate the concept of foreign keys with some practical examples using SQL. We'll create two tables, Customers and Orders, where each order is associated with a customer.

Step 1: Create the Customers Table

First, we create a table named Customers with a primary key:

SQL
1CREATE TABLE Customers (
2 CustomerID INT PRIMARY KEY,
3 FirstName VARCHAR(50),
4 LastName VARCHAR(50)
5);

Step 2: Create the Orders Table

Next, we create an Orders table and define a foreign key that references the CustomerID in the Customers table:

SQL
1CREATE TABLE Orders (
2 OrderID INT PRIMARY KEY,
3 OrderDate DATE,
4 CustomerID INT,
5 FOREIGN KEY (CustomerID) REFERENCES Customers(CustomerID)
6);

Explanation

  • Primary Key (CustomerID): In the Customers table, CustomerID is the primary key, ensuring each customer has a unique identifier.
  • Foreign Key (CustomerID): In the Orders table, CustomerID is a foreign key that references the CustomerID in the Customers table. This establishes a relationship between orders and customers.

Step 3: Insert Data

Let's insert some data into both tables to see how foreign keys work:

SQL
1-- Inserting data into Customers
2INSERT INTO Customers (CustomerID, FirstName, LastName) VALUES
3(1, 'John', 'Doe'),
4(2, 'Jane', 'Smith');
5
6-- Inserting data into Orders
7INSERT INTO Orders (OrderID, OrderDate, CustomerID) VALUES
8(101, '2023-01-15', 1),
9(102, '2023-02-20', 2);

Step 4: Query Data

Now, let's query the data to see how the foreign key relationship is maintained:

SQL
1SELECT Orders.OrderID, Orders.OrderDate, Customers.FirstName, Customers.LastName
2FROM Orders
3JOIN Customers ON Orders.CustomerID = Customers.CustomerID;
Output
OrderID | OrderDate    | FirstName | LastName
--------|------------|-----------|---------
101     | 2023-01-15 | John      | Doe
102     | 2023-02-20 | Jane      | Smith

Step 5: Handling Referential Integrity

Foreign keys also enforce referential integrity. For example, if you try to insert an order with a CustomerID that does not exist in the Customers table, SQL will raise an error:

SQL
1INSERT INTO Orders (OrderID, OrderDate, CustomerID) VALUES
2(103, '2023-03-10', 3);

Info

If you attempt to insert the above data, SQL will return an error because CustomerID 3 does not exist in the Customers table.

What's Next?

Now that you understand foreign keys and how they establish relationships between tables, the next step is learning how to insert data into these tables while maintaining referential integrity. This involves understanding constraints like ON DELETE and ON UPDATE, which define what happens when a referenced row is deleted or updated.

Stay tuned for more tutorials on SQL that will help you master database management and design!


PreviousPrimary KeysNext Constraints

Recommended Gear

Primary KeysConstraints