Welcome to our in-depth guide on SQL Foreign Key! In this tutorial, we'll cover everything you need to know about this essential database concept, from the basics to advanced examples. Let's dive in!
In a relational database, a Foreign Key is a field in one table that refers to the Primary Key of another table. Foreign Keys help establish a relationship between tables, enabling you to structure complex data efficiently.
To create a Foreign Key, you'll first need to create the tables you want to link and define their Primary Keys. Here's an example of creating two tables, employees and departments, and defining a Foreign Key in the employees table that references the department_id in the departments table:
CREATE TABLE departments (
department_id INT PRIMARY KEY,
department_name VARCHAR(255)
);
CREATE TABLE employees (
employee_id INT PRIMARY KEY,
first_name VARCHAR(255),
last_name VARCHAR(255),
department_id INT,
FOREIGN KEY (department_id) REFERENCES departments(department_id)
);In this example, we've created a Foreign Key department_id in the employees table that references the department_id in the departments table.
ALTER TABLE employees
ADD FOREIGN KEY (department_id)
REFERENCES departments(department_id)
ON DELETE CASCADE;ALTER TABLE employees
ADD CONSTRAINT FK_employees_departments
FOREIGN KEY (department_id)
REFERENCES departments(department_id)
ON UPDATE CASCADE;What does a Foreign Key do in a relational database?
That's it for our SQL Foreign Key tutorial! We've covered the basics, the importance of Foreign Keys, and some advanced concepts. Happy coding! 🚀