
For an instructor lead, in-depth look at learning SQL click below.
Welcome to the world of SQL programming! Today, we will dive into understanding a pivotal concept in SQL, known as the ‘Foreign Key’. If you are stepping into the database field, this is an essential concept you need to familiarize yourself with.
Overview of SQL Foreign Key
A Foreign Key is a column or combination of columns in SQL, used to establish a link between the data in two tables. It acts as a cross-reference between tables because it references the primary key of another table, thereby creating a link between them. Basically, a foreign key in one table is used to “point” to the primary key in another table.
Why Use a Foreign Key?
Foreign Keys play an integral role in maintaining the integrity of the data. It prevents actions that would destroy links between tables. A foreign key ensures that the row of information in Table A has corresponding data in Table B.
Declaring Foreign Keys in SQL
You can declare a Foreign Key in SQL when you are creating or altering a table.
1 2 3 4 5 6 7 8 9 |
CREATE TABLE Orders ( OrderID int NOT NULL, OrderNumber int NOT NULL, CustomerID int, PRIMARY KEY (OrderID), FOREIGN KEY (CustomerID) REFERENCES Customers(CustomerID) ); |
In the above SQL code, an Orders table is being created. The ‘CustomerID’ field is being declared as a foreign key, which references the CustomerID from the Customers table. This means that for every record in the Orders table, there should be a corresponding record in the Customers table.
1 2 3 4 |
ALTER TABLE Orders ADD FOREIGN KEY (CustomerID) REFERENCES Customers(CustomerID); |
Whereas in this SQL code, a foreign key ‘CustomerID’ is being added to an existing Orders table. Note that a Foreign key must have corresponding value in the referenced table, or else the insert/update action will fail.
Conclusion
Understanding foreign keys in SQL and their usage is important when dealing with relational databases. It helps ensure the integrity and reliability of the data, making it easier for you to work with and manipulate your data according to the needs of your application. Happy coding!
1 |