For working professionals
For fresh graduates
More
The concept of foreign keys in Structured Query Language (SQL) is fundamental to database administration and helps to preserve data integrity.
The Foreign key has always played an important role in ensuring the coherence and reliability of stored data. This has happened even in the early days of relational databases.
In this guide, we will discuss what a Foreign key in SQL is all about. We will look at its syntax and practical applications through examples.
Foreign Keys are vital parts of relational database administration. They make it easier for tables to connect meaningfully with one another. Foreign Keys guarantee the accuracy and consistency of data relationships by enforcing referential integrity. This prevents the entry of invalid or orphaned data.
You will have a thorough grasp of Foreign Keys in SQL and how they may improve the dependability and efficiency of your database systems by the end of this guide.
A Foreign Key in SQL is an important component for maintaining the links between tables in a relational database.
When you establish a foreign key constraint, you are essentially specifying a column (or columns) in one table that refers to the primary key in another table. This establishes a parent-child connection between the two tables, with the parent table being the table having the primary key and the child table being the table containing the foreign key.
A Foreign Key and a Primary Key in SQL are different. In SQL, a Primary Key uniquely identifies each record in a table, while a Foreign Key establishes a relationship between two tables by referencing the Primary Key of another table. So Primary and Foreign Keys in SQL are different
Syntax of the Foreign Key SQL query:
CREATE TABLE table_name (
column1 data_type,
column2 data_type,..,
FOREIGN KEY (column_name)
REFERENCES referenced_table_name (referenced_column_name)
);
Let's now examine an example and provide an explanation:
Assume that ‘Employees’ and ‘Departments’ are our two tables.
Departments Table:
DepartmentID | DepartmentName |
1 | Human Resources |
2 | Finance |
3 | Marketing |
Employees Table:
EmployeeID | FirstName | LastName | DepartmentID |
1 | John | Doe | 1 |
2 | Jane | Smith | 2 |
3 | Michael | Johnson | 3 |
Each employee belongs to a department, and we want to ensure that the department referenced by an employee exists in the ‘Departments’ table.
We would use these commands: CREATE TABLE Employees (
EmployeeID INT PRIMARY KEY,
FirstName VARCHAR(50),
LastName VARCHAR(50),
DepartmentID INT,
FOREIGN KEY (DepartmentID) REFERENCES Departments(DepartmentID)
);
CREATE TABLE Departments (
DepartmentID INT PRIMARY KEY,
DepartmentName VARCHAR(50)
);
Here are two ways to add a Foreign Key in SQL:
When you are creating a new table and want to establish a foreign key relationship right away, you can incorporate the FOREIGN KEY constraint within the CREATE TABLE statement. Here is the Foreign Key SQL syntax during table creation:
CREATE TABLE table_name (
column1 data_type,
column2 data_type,
...
FOREIGN KEY (column_name) REFERENCES referenced_table_name(referenced_column_name)
);
Let's consider an example: To create a foreign key in orders table during creation:
CREATE TABLE orders (
order_id INT PRIMARY KEY,
customer_id INT,
order_date DATE,
FOREIGN KEY (customer_id) REFERENCES customers(customer_id)
);
In this example, the customer_id column in the orders table is designated as a Foreign Key, referencing the customer_id column in the ‘customers’ table. This ensures that any value entered in the customer_id column of the ‘orders’ table must already exist in the ‘customers’ table, maintaining referential integrity.
Table Created During Table Creation:
order_id | customer_id | order_date |
If you have an existing table and need to establish a Foreign Key relationship afterward, you can utilize the ALTER TABLE statement along with the ADD CONSTRAINT clause. Here is the syntax to add a Foreign Key in SQL after table creation.
ALTER TABLE table_name
ADD CONSTRAINT constr_name FOREIGN KEY (col_nam)
REFERENCES referd_tablecreated(referenced_columnnamecreated);
Let's illustrate with an example. To add a Foreign Key after the creation of an ‘orders’ table, use this command.
ALTER TABLE orders
ADD CONSTRAINT fk_custid FOREIGN KEY (customer_id) REFERENCES customers(cust_id);
Here, the FOREIGN KEY constraint named 'fk_custid' is added to the ‘orders’ table. The cust_id column in the ‘orders’ table is linked to the cust_id column in the ‘customers’ table, ensuring that each value in the cust_id column of the ‘orders’ table corresponds to a valid entry in the ‘customers’ table, thus preserving referential integrity.
Table Created After Table Creation:
order_id | customer_id | order_date |
When inserting records into a table with Foreign Keys, you must ensure that the values you are inserting into the Foreign Key columns exist in the referenced table.
For instance, let's say we have two tables: ‘orders’ and ‘customers’. A Foreign Key field called customer_id in the ‘orders’ table refers to the customer_id column in the ‘customers’ table. Here is how you can insert records into the ‘orders’ table:
INSERT INTO orders (order_id, customer_id, order_date) VALUES
(1, 101, '2023-03-15'),
(2, 102, '2023-03-16'),
(3, 103, '2023-03-17');
Ensure that the customer_id values (101, 102, 103) exist in the ‘customers’ table before executing the above insert statement. We would now have an output table like this:
order_id | customer_id | order_date |
1 | 101 | 2023-03-15 |
2 | 102 | 2023-03-16 |
3 | 103 | 2023-03-17 |
To drop a Foreign Key constraint, you can use the ALTER TABLE statement with the DROP CONSTRAINT clause. For example, to drop a foreign key named fk_customer_id from the ‘orders’ table, you would use the following SQL:
ALTER TABLE orders DROP CONSTRAINT fk_customer_id;
This command removes the foreign key constraint fk_customer_id from the ‘orders’ table.
A table can have multiple Foreign Keys to establish relationships with different tables. For instance, consider a scenario where we need to record transactions where each user acts as both a buyer and a seller. Here's an example:
CREATE TABLE Transactions (
transaction_id INT PRIMARY KEY,
amount INT,
seller INT,
buyer INT,
CONSTRAINT fk_sel FOREIGN KEY (theseller) REFERENCES Users(id),
CONSTRAINT fk_buy FOREIGN KEY (thebuyer) REFERENCES Users(id)
);
In this example, the ‘Transactions’ table contains two Foreign Keys (seller and buyer), both referencing the id column in the ‘Users table. This allows us to maintain relationships
between transactions and users acting as buyers or sellers.
Output Table:
transaction_id | amount | seller | buyer |
This represents the ‘Transactions’ table where transactions are recorded, with two foreign keys (seller and buyer) referencing the id column in the ‘Users’ table.
Foreign keys play a crucial role in maintaining data integrity and establishing relationships between tables in a relational database. Here are several reasons why you should utilize Foreign Keys:
Foreign Keys aid in normalizing data across multiple tables, reducing redundancy and improving database efficiency. By breaking down large datasets into smaller and related tables, you can organize data logically and prevent duplication.
For example, in a database for an e-commerce platform, you might have separate tables for customers, orders, and products. The use of Foreign Keys allows you to link these tables together based on relationships, such as associating each order with a specific customer.
Foreign Keys help enforce referential integrity, ensuring that only valid data can be inserted into related tables. When a Foreign Key constraint is applied, it restricts the values that can be entered into a column to those that exist in the referenced table's primary key column. By doing this, errors and inconsistencies in the database are avoided.
Foreign Keys facilitate maintaining consistency across related tables by enforcing data relationships. When you update or delete records in one table, the Foreign Key constraints automatically ensure that corresponding changes are made in related tables, preserving data integrity.
For example, in a database for a library, if a book record is deleted, Foreign Key constraints ensure that associated records, such as borrowing history or book availability, are also appropriately updated or removed.
By defining Foreign Key relationships between tables, SQL databases can optimize query performance through efficient indexing and query execution plans. This allows for faster data retrieval and manipulation operations, leading to improved overall system performance.
For instance, in a database for a social media platform, Foreign Keys can expedite searching for posts by a specific user by leveraging indexed foreign key columns.
Foreign Keys promote data consistency and accuracy by preventing or restricting the insertion of invalid or inconsistent data into related tables. This ensures that the database remains reliable and trustworthy, supporting robust decision-making processes.
In a database tracking employee information and their assigned departments, Foreign Keys ensures that only existing department IDs can be assigned to employees, eliminating errors in department assignments.
Foreign Keys enforce data integrity by preventing orphaned records and maintaining the referential integrity of the database. Orphaned records, which are records in a child table that no longer have a corresponding record in the parent table, are prevented by Foreign Key constraints. This ensures that all data in the database remains valid and consistent, minimizing the risk of data corruption and ensuring the reliability of the database.
When it comes to implementing Foreign Keys in SQL databases, the syntax may vary slightly depending on the Database Management System (DBMS) you are using. Let's discuss the Foreign Key syntax for MySQL, SQL Server, Oracle, and MS Access in a tabular format:
Database | Overview | Syntax |
MySQL | MySQL supports the definition of Foreign Key constraints within table creation statements using the FOREIGN KEY keyword. | sql CREATE TABLE table_name ( the_column1 data_type, ... FOREIGN KEY (the_colname) REFERENCES the_table_referenced(referenced_col) ); |
SQL Server | SQL Server allows you to define Foreign Key constraints within table creation statements using the CONSTRAINT keyword. | sql CREATE TABLE table_name ( column1 data_type, column2 data_type, ... CONSTRAINT constraint_name FOREIGN KEY (column_name) REFERENCES referenced_table_name(referenced_column_name) ); |
Oracle | Oracle utilizes the CONSTRAINT keyword to define Foreign Key constraints within table creation statements. | sql CREATE TABLE table_name ( column1 data_type, column2 data_type, ... CONSTRAINT constraint_name FOREIGN KEY (column_name) REFERENCES referenced_table_name(referenced_column_name) ); |
MS Access | MS Access also supports Foreign Key constraints, and the syntax is similar to other databases. | sql CREATE TABLE table_name ( column1 data_type, column2 data_type, ... CONSTRAINT constraint_name FOREIGN KEY (column_name) REFERENCES referenced_table_name(referenced_column_name) ); |
In summary, Foreign Keys in SQL are really important for keeping your data organized and accurate. They help make sure that the relationships between different parts of your database are strong and reliable.
By using Foreign Keys, you can prevent mistakes and make your database work better. Using Foreign Keys is a smart move that can make a big difference in how well your database works. This is true whether you're setting up a new database or changing an existing one,
With the knowledge you have gained from this guide, you will be able to use Foreign Keys effectively and improve the quality of your database.
ADD CONSTRAINT fk_name
FOREIGN KEY (foreign_key_column)
REFERENCES parent_table(primary_key_column);
Rohan Vats
Software Engineering Manager @ upGrad. Passionate about building large scale web apps with delightful experiences. In pursuit of transforming eng…Read More
Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)
Indian Nationals
1800 210 2020
Foreign Nationals
+918045604032
1.The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.
2.The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not provide any a.