In SQL, a foreign key is a field or a set of fields in a table that refers to the primary key or a unique key in another table.
It establishes a link or relationship between the data in two tables, enforcing referential integrity.
The use of foreign keys helps maintain consistency in a relational database by ensuring that values in one table correspond to valid values in another table.
CREATE TABLE employees ( employee_id INT PRIMARY KEY, first_name VARCHAR(50), last_name VARCHAR(50), department_id INT ); CREATE TABLE departments ( department_id INT PRIMARY KEY, department_name VARCHAR(50) );
The employees table has a column named department_id that is intended to store the department to which each employee belongs.
The departments table has a primary key column named department_id.
ALTER TABLE employees ADD CONSTRAINT fk_department FOREIGN KEY (department_id) REFERENCES departments(department_id);
fk_department is the name of the foreign key constraint. We can choose any meaningful name for your foreign key constraint.
FOREIGN KEY (department_id) specifies the column in the employees table that will act as the foreign key, referencing the department_id column in the departments table.
REFERENCES departments(department_id) indicates the target table (departments) and the column in that table that is being referenced (department_id).