The Wayback Machine - https://web.archive.org/web/20241127044612/https://www.geeksforgeeks.org/foreign-key-constraint-in-sql/
Open In App

SQL FOREIGN KEY Constraint

Last Updated : 15 Jun, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

The SQL FOREIGN KEY constraint The foreign key constraint ensures that the values in the foreign key column match the values in the primary key column of the referenced table, maintaining referential integrity.

Foreign Key in SQL

A foreign key is a column or a combination of columns in a table that establishes a link between two tables in a relational database. It refers to the primary key in another table, creating a relationship between them.

The table with a foreign key is called a foreign table/child table/referencing table and the table with a primary key that is referenced by a foreign key is called a primary table/parent table /referenced Table.

Syntax

A foreign key can be created during table creation using CREATE TABLE statement or it can be added to a table later using ALTER TABLE statement

SQL FOREIGN KEY on CREATE TABLE

The syntax to create a foreign key in CREATE TABLE statement is:

CREATE TABLE table_name (
column1 datatype,
column2 datatype,
…,
CONSTRAINT fk_constraint_name FOREIGN KEY (column1, column2, …)
REFERENCES parent_table(column1, column2, …)

);

SQL FOREIGN KEY on ALTER TABLE

The syntax to add a foreign key with ALTER TABLE statement is:

ALTER TABLE table_name
ADD CONSTRAINT fk_constraint_name FOREIGN KEY (column1, column2, …)
REFERENCES parent_table(column1, column2, …);

SQL Foreign Key Constraint Example

In this example, we create a foreign key during the table creation.

Query

SQL
CREATE TABLE Customers (
  CustomerID INT PRIMARY KEY,
  CustomerName VARCHAR(50) NOT NULL
);

CREATE TABLE Orders (
  OrderID INT PRIMARY KEY,
  OrderNumber INT NOT NULL,
  CustomerID INT,
  FOREIGN KEY (CustomerID) REFERENCES Customers(CustomerID)
);

INSERT INTO Customers (CustomerID, CustomerName)
VALUES (1, 'John'), (2, 'Jane'), (3, 'Bob');

INSERT INTO Orders (OrderID, OrderNumber, CustomerID)
VALUES (1, 101, 1), (2, 102, 2), (3, 103, 3);

The following query will create the ‘customers’ and ‘orders’ table.

Customers Table

CustomerID (Primary Key)CustomerName
1John
2Jane
3Bob
OrderID (Primary Key)OrderNumberCustomerID (Foreign Key)
11011
21022
31033

Insert Value in Foreign Key Table

If a corresponding value in the foreign table doesn’t exist, a record in the child table cannot be inserted.

Query:

INSERT INTO Orders (OrderID, OrderNumber, CustomerID)
VALUES (4, 104, 4);

Output : 

Error: FOREIGN KEY constraint failed.

Delete a value in Foreign Key Table

When a record in the master table is deleted and the corresponding record in the child table exists, an error message is displayed and prevents the DELETE operation from going through.

Query:

DELETE FROM Customers 
WHERE CustomerID = "3";

Output:

Error: FOREIGN KEY constraint failed

SQL DROP FOREIGN KEY

To remove a foreign key from a table, use the ALTER TABLE with DROP CONSTRAINT command.

Syntax

Syntax to remove any foreign key from a table:

ALTER TABLE table_name DROP CONSTRAINT fk_name;

Important Points About SQL FOREIGN KEY Constraint

  • A FOREIGN KEY is a field (or collection of fields) in one table, that refers to the PRIMARY KEY in another table.
  • The table containing the foreign key is called the child table, and the table containing the candidate key is called the referenced or parent table.
  • A table can have multiple FOREIGN KEY constraints.
  • When defining a FOREIGN KEY constraint, you can specify what happens when a referenced row in the parent table is deleted or updated. This is done using the ON DELETE and ON UPDATE clauses followed by the CASCADE, SET NULL, or NO ACTION option.
  • The FOREIGN KEY constraint in SQL is used to maintain the referential integrity of data within the database.

Previous Article
Next Article

Similar Reads

SQL Query to Drop Foreign Key Constraint Using ALTER Command
A foreign key is included in the structure of a table, to connect multiple tables by referring to the primary key of another table. Sometimes, you might want to remove the primary key constraint from a table for performance issues or other requirements. A foreign key constraint can be removed from a table using the ALTER TABLE command and DROP CONS
3 min read
How to Temporarily Disable a Foreign Key Constraint in MySQL?
MySQL is a popular open-source relational database management system (RDBMS) that is uniquely used to construct expandable and high-productivity databases. MySQL, which was created by MySQL AB and later acquired by its current owner Oracle Corporation, was originally introduced in 1995. MySQL is reputed for its sturdy and quick functioning attribut
4 min read
MySQL FOREIGN KEY Constraint
A FOREIGN KEY is a field/column(or collection of fields) in a table that refers to a PRIMARY KEY in another table. It is used for linking one or more than one table together. FOREIGN KEY is also called referencing key. A Foreign key creates a link (relation) between two tables thus creating referential integrity. In this article, we will learn abou
7 min read
Can a Composite Key be a Foreign Key in Another Table?
Answer: Yes, a composite key can be used as a foreign key in another table within a relational database.In SQL databases, a composite key comprises multiple columns to uniquely identify rows in a table. To establish a foreign key referencing a composite key: Create the Parent TableDefine the parent table with a composite key. CREATE TABLE ParentTab
1 min read
How to Create a Table With a Foreign Key in SQL?
To create a table with a foreign key in SQL, use the FOREIGN KEY constraint on the column which is the desired foreign key. SyntaxTo create a table with a foreign key in SQL, use the following syntax: CREATE TABLE TABLE_NAME( Column 1 datatype, Column 2 datatype, Column 3 datatype FOREIGN KEY REFERENCES Table_name(Column name), .. Column n ) Create
3 min read
SQL Query to Add Foreign Key Constraints Using ALTER Command
In relational databases, a Foreign Key Constraint is a fundamental concept that defines a relationship between two tables. It ensures that the value of one or more columns in a child table corresponds to the value in a primary key or unique key in a parent table. In this article, we will look into how we can add a foreign key constraint using the A
3 min read
PL/SQL Foreign Key
Maintaining data integrity is essential in relational database management systems. One essential concept in ensuring data consistency is the use of foreign keys. In PL/SQL, a foreign key creates relationships between tables, ensuring that the data in one table corresponds to the data in another. This article will explore the concept of foreign keys
8 min read
Foreign key in MS SQL Server
A foreign key in SQL Server plays a crucial role in establishing and enforcing relationships between tables. It is a column or a set of columns in a table that references the primary key or a unique key in another table. By using foreign key constraints the SQL Server keeps data consistent between related tables. In this article, We will learn abou
6 min read
Can a Foreign Key be NUll in SQL Server?
In SQL Server, foreign keys are essential to maintaining relationships between tables and enforcing referential integrity. A foreign key is a column (or set of columns) in a child table that references a primary key in a parent table and ensures that the data in both tables remains consistent. However, a common question that arises during database
4 min read
How to Index Foreign Key Columns in SQL Server
Indexing foreign key columns in SQL Server is a vital optimization strategy for enhancing query performance, particularly when dealing with JOIN operations between related tables. Foreign keys enforce relationships between tables by linking a column (or columns) in one table to the primary key of another, and indexing these columns improves query s
4 min read
SQL PRIMARY KEY Constraint
SQL PRIMARY KEY constraint uniquely identifies each record in a database table. PRIMARY KEY in SQLPRIMARY KEY in SQL is a column (or group of columns) that uniquely identifies the records in that table. A primary key must contain unique values and can not have any NULL value. There can only be one primary key in a table, but that primary key can co
3 min read
How to add a foreign key using ALTER in MySQL
In this article, we will discuss the overview of foreign keys and will discuss how to add a foreign key using ALTER in MySQL step by step. Let's discuss it one by one. Foreign key : If an attribute is a primary key in one table but was not used as a primary key in another table then the attribute which is not a primary key in the other table is cal
3 min read
SQLite Foreign Key
SQLite is a serverless architecture, which does not require any server or administrator to run or process queries. This database system is used to develop embedded software due to its lightweight, and low size. It is used in Desktop applications, mobile applications televisions, and so on. Foreign Key in SQLiteA Foreign Key is a column or set of co
3 min read
Foreign Key in MariaDB
MariaDB is an open-source database system which is similar to MySQL. It provide various features such as high availability and vertical scalability to allow database to scale up over various nodes or single node as features like Galera Cluster in MariaDB. The Foreign keys are the most important features that help define and establish relationships
6 min read
Foreign Key Indexing and Performance in PostgreSQL
As the world of databases is always changing, PostgreSQL is one of the autonomous options because of its dependability, capability to handle huge amounts of data, and fast performance. Effective indexing, especially for foreign keys, is an important key for enhancing the speed of PostgreSQL. Appropriate indexes for foreign keys can greatly speed up
4 min read
MySQL Deleting Rows When There is a Foreign Key
To delete a row with a foreign key in MySQL, use the CASCADE keyword while creating a foreign key. Using the ON DELETE CASCADE clause in MySQL, all matching rows from the child table are deleted when the referencing rows from the parent table are deleted. This helps in maintaining the referential integrity of the table. SyntaxFOREIGN KEY (col_name)
2 min read
Foreign Key with a Null Value in MySQL
In databases, foreign keys are like links connecting two tables. They make sure that data in one table matches data in another. But a common question is whether a foreign key can be NULL. In this article, We will explain what NULL values mean for foreign keys, how they work with the help of examples and so on. What is Foreign Key?A foreign key is a
5 min read
PostgreSQL - Foreign Key
Foreign keys play a crucial role in relational databases by establishing relationships between tables and safeguarding data integrity. In this PostgreSQL foreign key tutorial, we'll cover how foreign keys work, their importance and how to create them. We will also learn about foreign key constraints and their role in ensuring data consistency. By t
5 min read
Foreign Key with a Null Value in PostgreSQL
PostgreSQL supports foreign keys to ensure referential integrity between tables. Nullable foreign keys add flexibility by allowing child table rows to either reference a parent table or have a NULL value, meaning no association. While this is useful in certain cases, managing nullable foreign keys carefully is important to maintain data integrity.
6 min read
How to Create a Table With Multiple Foreign Keys in SQL?
When a non-prime attribute column in one table references the primary key and has the same column as the column of the table which is prime attribute is called a foreign key. It lays the relation between the two tables which majorly helps in the normalization of the tables. A table can have multiple foreign keys based on the requirement. In this ar
2 min read
How to List all Foreign Keys Referencing a Given Table in SQL Server?
SQL Server is a Relational Database Management System(RDBMS) that allows users to create and manage databases efficiently. In SQL Server, understanding the table's relationship is very important for database design and maintenance. Foreign keys play an important role in establishing relations between different tables. In this article, we will learn
5 min read
Unique Constraint in MS SQL Server
A table might have repetitive data in form of rows. This might cause glitches while retrieving data from the query. To avoid them, a unique constraint is used. Unique allows sorting a column or set of columns uniquely meaning, a user cannot insert a duplicate or repeated value in a column as it results in an error. A unique constraint is enforced i
2 min read
Check Constraint in MS SQL Server
Check Constraint : It is used alongside relational operators to check whether a value satisfies the condition or not (boolean). If the condition is satisfied, the boolean expression sets to True otherwise False. The check constraint does not have a specific syntax. It is used along with the create table syntax. Syntax : Create table Marks name varc
2 min read
SQL | DEFAULT Constraint
The DEFAULT Constraint is used to fill a column with a default and fixed value. The value will be added to all new records when no other value is provided. Syntax CREATE TABLE tablename (Columnname DEFAULT 'defaultvalue' ); Using DEFAULT on CREATE TABLE To set a DEFAULT value for the "Location" column when the "Geeks" table is created. Query: CREAT
1 min read
How to Use SQL Query to Rename a Constraint?
In SQL, we sometimes need to rename the constraints of a table. The whole process for doing the same is demonstrated below. For this article, we will be using the Microsoft SQL Server as our database. Step 1: Create a Database. For this use the below command to create a database named GeeksForGeeks. Query: CREATE DATABASE GeeksForGeeksOutput: Step
2 min read
SQL DROP CONSTRAINT
In SQL, the DROP CONSTRAINT command is used to remove constraints from the columns of a table. Constraints are used to limit a column on what values it can take. We add constraints to our columns while we are creating the structure of tables in SQL and when we are actually inserting values in those tables sometimes we find that there is no further
3 min read
SQL Server NOT NULL Constraint
The SQL Server NOT NULL constraint is used to ensure that when we insert the rows to the table the column is never NULL. It throws an error when there is no value for a particular column when it is with a NOT NULL constraint. The primary key by default comes with the NOT NULL and UNIQUE constraints so the primary key can't be NULL at any time. The
5 min read
SQL Server DEFAULT Constraint
The DEFAULT constraint is used to set the default value of the column as some value so that later it can be updated or if the value of a column cell is not changed the default will remain. If we don't add the DEFAULT constraint to a column the SQL's default will be set which is NULL. Syntax:CREATE TABLE table_name(column1 data_type,column2 data_typ
3 min read
SQL | UNIQUE Constraint
SQL Constraints Unique constraints in SQL is used to check whether the sub-query has duplicate tuples in its result. It returns a boolean value indicating the presence/absence of duplicate tuples. Unique constraint returns true only if the subquery has no duplicate tuples, else it returns false. Important PointsEvaluates to true on an empty subquer
5 min read
How to Create Unique Constraint With NULL Columns in SQL Server
SQL Server is a versatile database developed by Microsoft and is one of the most used databases in the world. It provides the developer with a set of functionalities to create tables, insert data in them and then manipulate and play with them as and when necessary. In this article, we are going to see how we can create unique constraints with NULL
6 min read
Article Tags :
three90RightbarBannerImg