SQL Query to Add Foreign Key Constraints Using ALTER Command
Last Updated :
21 Aug, 2024
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 ALTER command in SQL.
Foreign Key Constraint
- A Foreign Key Constraint in a relational database is a rule that establishes a relationship between two tables.
- It ensures that the values in a column (or a group of columns) of one table (called the child table) must match the values in a column (or a group of columns) in another table (called the parent table).
- The column(s) in the parent table is referred to as the primary key or unique key, and the column(s) in the child table that references this primary key is the foreign key.
Create a Database:
We can create a Database using the command:
Syntax:
CREATE DATABASE DATABASE_NAME;
So let's create a geeks database as shown below:
CREATE DATABASE geeks;
Output:

Using Database:
Use the below command to use the geeks database:
use geeks;
Output:

Adding table into Database:-
To add a table into the database we use the below command:
Syntax:-
CREATE TABLE table_name (Attribute_name datatype...);
So, let's create a geeks table within the geeks database as shown below:
CREATE TABLE geeks(id int , name varchar(20));
Output:

Here Table Added Successfully.
Inserting values into Tables:
For inserting records into the table we can use the below command:
Syntax:
INSERT INTO table_name(column1,
column2,
column 3,.....)
VALUES( value1,
value2,
value3,.....);
So let's add some records in the geeks table:
INSERT INTO geeks(id,name) VALUES (1,"teja");
Output:

Creating Primary Key Element in a Table:
To have a Foreign Key in a Table we must have a Primary Key. To create a Primary we use the below command:
Syntax:
CREATE TABLE table_name (Attribute_name datatype PRIMARY_KEY);
Now let's create a primary key:
CREATE TABLE emp (id int NOT NULL PRIMARY KEY,name varchar(20))
Output:

Now to add a Foreign Key we have to create a new table by the following:
CREATE TABLE student(
id int ,
name varchar(20),
Emp_id int REFERENCES emp(id));
Output:

Alter a Table and ADD Foreign Key:
So if you already created the table student, and now you wish to add Foreign Key you can use the below command to change that:
ALTER TABLE dbo.student
add constraint Fk_empid foreign key(emp_id)
references dbo.emp(id);
Output:

At this point, we have successfully achieved our goal.
Conclusion
The Foreign Key Constraint is a crucial component in relational database management. It helps ensure the integrity and accuracy of your data by linking related records between different tables. By defining these relationships, you can prevent the entry of invalid data and establish clear connections between tables for more structured data management.
Similar Reads
SQL Interview Questions Are you preparing for a SQL interview? SQL is a standard database language used for accessing and manipulating data in databases. It stands for Structured Query Language and was developed by IBM in the 1970's, SQL allows us to create, read, update, and delete data with simple yet effective commands.
15+ min read
SQL Tutorial Structured Query Language (SQL) is the standard language used to interact with relational databases. Whether you want to create, delete, update or read data, SQL provides the structure and commands to perform these operations. SQL is widely supported across various database systems like MySQL, Oracl
8 min read
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
SQL Commands | DDL, DQL, DML, DCL and TCL Commands SQL commands are crucial for managing databases effectively. These commands are divided into categories such as Data Definition Language (DDL), Data Manipulation Language (DML), Data Control Language (DCL), Data Query Language (DQL), and Transaction Control Language (TCL). In this article, we will e
7 min read
SQL Joins (Inner, Left, Right and Full Join) SQL joins are fundamental tools for combining data from multiple tables in relational databases. Joins allow efficient data retrieval, which is essential for generating meaningful observations and solving complex business queries. Understanding SQL join types, such as INNER JOIN, LEFT JOIN, RIGHT JO
5 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
Normal Forms in DBMS In the world of database management, Normal Forms are important for ensuring that data is structured logically, reducing redundancy, and maintaining data integrity. When working with databases, especially relational databases, it is critical to follow normalization techniques that help to eliminate
7 min read
Class Diagram | Unified Modeling Language (UML) A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
SQL Query Interview Questions SQL or Structured Query Language, is the standard language for managing and manipulating relational databases such as MySQL, Oracle, and PostgreSQL. It serves as a powerful tool for efficiently handling data whether retrieving specific data points, performing complex analysis, or modifying database
15+ min read
Backpropagation in Neural Network Back Propagation is also known as "Backward Propagation of Errors" is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network.It works iteratively to adjust weights and
9 min read