foreign key in sql

Galaxy Glossary

What is a foreign key constraint and how does it enforce data integrity?

A foreign key constraint in SQL links tables together by referencing a primary key in another table. This ensures data consistency and avoids orphaned records. It's a crucial part of relational database design.
Sign up for the latest in SQL knowledge from the Galaxy Team!
Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.

Description

Foreign keys are a fundamental aspect of relational database design. They establish relationships between tables, ensuring data integrity and preventing inconsistencies. Imagine you have a table of customers and a table of orders. A foreign key in the orders table would reference the customer ID in the customers table. This means each order must correspond to an existing customer. Without a foreign key, you could potentially add an order for a non-existent customer, leading to data inaccuracies. Foreign keys enforce this link, preventing such issues. They are crucial for maintaining the accuracy and consistency of data across multiple tables. A well-designed database with foreign keys ensures that data in related tables is always valid and consistent. For example, if a customer is deleted from the customers table, any orders associated with that customer will automatically be flagged as invalid or potentially deleted, preventing orphaned records.

Why foreign key in sql is important

Foreign keys are essential for maintaining data integrity in relational databases. They prevent invalid data from being entered and ensure relationships between tables are consistent. This leads to more reliable and accurate data analysis and reporting.

Example Usage

```sql -- Create the Customers table CREATE TABLE Customers ( CustomerID INT PRIMARY KEY, FirstName VARCHAR(50), LastName VARCHAR(50) ); -- Create the Orders table CREATE TABLE Orders ( OrderID INT PRIMARY KEY, CustomerID INT, OrderDate DATE, FOREIGN KEY (CustomerID) REFERENCES Customers(CustomerID) ); -- Insert some data into Customers INSERT INTO Customers (CustomerID, FirstName, LastName) VALUES (1, 'John', 'Doe'), (2, 'Jane', 'Smith'); -- Insert some data into Orders INSERT INTO Orders (OrderID, CustomerID, OrderDate) VALUES (101, 1, '2024-01-15'), (102, 2, '2024-01-20'); -- Attempt to insert an order for a non-existent customer (will fail) INSERT INTO Orders (OrderID, CustomerID, OrderDate) VALUES (103, 3, '2024-01-25'); ```

Common Mistakes

Want to learn about other SQL terms?