What is Foreign key in a table
Foreign key is a column in one table which is primary key on another table. Foreign key and Primary key is used to define relationship between two tables in relational database. For example in Employe and Department relationship, we have two tables Department(dept_id, dept_name) and Employee(emp_id, emp_name, dept_id). dept_id is primary key in Department table and foreign key in Employeetable. Though it’s not require that name of foreign key must be same with primary key, we have kept it same as per standard SQL best practices. Foreign key in a table enforce Referential Integrity constraint, which can be used to implement business rules e.g. referential integrity can stop you from creating an Employee with a non existent department. This kind of check maintains integrity of data in a relationship. As discussed in our post What is referential integrity in MySQL database, we have seen that it's implemented as foreign key constraint and can allow CASCADE UPDATE and DELETE. These referential action delete or update matching column in child table ( foreign key table) when corresponding row from parent table (primary key table ) is deleted or updated to maintain integrity of data.