Golang Tutorials - Learn Go Programming with Easy Step-by-Step Guides

Explore comprehensive Golang tutorials for beginners and advanced programmers. Learn Go programming with easy-to-follow, step-by-step guides, examples, and practical tips to master Go language quickly.

Foreign Key in SQL

Foreign Key in SQL

? Foreign Key in SQL

A Foreign Key is a constraint used to link two tables together. It enforces a relationship between columns in two tables, ensuring referential integrity by restricting the values in the child table to only those that exist in the parent table.


? Key Concepts:

  • Parent Table: The table with the primary key (or unique key).

  • Child Table: The table with the foreign key referencing the parent.

  • Ensures that the child table cannot have values in the foreign key column that do not exist in the parent table.


? Syntax for Creating a Foreign Key:

When creating a table:

CREATE TABLE Orders (    OrderID int PRIMARY KEY,    CustomerID int,    FOREIGN KEY (CustomerID) REFERENCES Customers(CustomerID));

Adding a foreign key to an existing table:

ALTER TABLE OrdersADD CONSTRAINT fk_customerFOREIGN KEY (CustomerID) REFERENCES Customers(CustomerID);

? Example:

Suppose you have two tables:

CREATE TABLE Customers (    CustomerID int PRIMARY KEY,    CustomerName varchar(100));CREATE TABLE Orders (    OrderID int PRIMARY KEY,    CustomerID int,    OrderDate date,    FOREIGN KEY (CustomerID) REFERENCES Customers(CustomerID));
  • CustomerID in Orders must match a CustomerID in Customers.

  • You cannot insert an order with a CustomerID that does not exist in Customers.


? Foreign Key Actions (optional):

You can specify what happens on DELETE or UPDATE of the parent row:

FOREIGN KEY (CustomerID) REFERENCES Customers(CustomerID)ON DELETE CASCADEON UPDATE CASCADE;
  • CASCADE: Automatically delete/update child rows.

  • SET NULL: Set child foreign key to NULL.

  • RESTRICT: Prevent the delete/update if there is a child row (default in many systems).


? Benefits of Foreign Keys:

  • Maintains data integrity.

  • Prevents orphan records.

  • Defines relationships between tables for joins.


If you want, I can help you write foreign keys for your specific table structure or explain how to handle cascading options!

Disclaimer for AI-Generated Content:
The content provided in these tutorials is generated using artificial intelligence and is intended for educational purposes only.
html
docker
php
kubernetes
golang
mysql
postgresql
mariaDB
sql