The Anubhav portal was launched in March 2015 at the behest of the Hon'ble Prime Minister for retiring government officials to leave a record of their experiences while in Govt service .
A foreign key in Microsoft SQL Server is used to link two tables together and enforce
data integrity. It ensures that values in one table must exist in another.
Basic Concept
Parent Table → contains Primary Key
Child Table → contains Foreign Key
Example:
Customers (Parent)
Orders (Child)
Step 1: Create Parent Table
CREATE TABLE Customers (
CustomerID INT PRIMARY KEY,
Name NVARCHAR(100)
);
FOREIGN KEY (CustomerID)
REFERENCES Customers(CustomerID)
ON DELETE CASCADE
ON UPDATE CASCADE
Options:
CASCADE → delete/update child automatically
SET NULL → set FK to NULL
NO ACTION → prevent operation (default)
Check Foreign Keys in Database
SELECT
fk.name AS ForeignKey,
OBJECT_NAME(fk.parent_object_id) AS ChildTable,
OBJECT_NAME(fk.referenced_object_id) AS ParentTable
FROM sys.foreign_keys fk;
Real-World Use Cases
Orders → Customers
Posts → Users
Comments → Posts
Best Practices
Always index foreign key columns
Use meaningful constraint names
Use cascade carefully (avoid accidental mass deletes)
Keep data types same in both tables
Join MindStick Community
You need to log in or register to vote on answers or questions.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
A foreign key in Microsoft SQL Server is used to link two tables together and enforce data integrity. It ensures that values in one table must exist in another.
Basic Concept
Example:
Customers(Parent)Orders(Child)Step 1: Create Parent Table
Step 2: Create Child Table with Foreign Key
How It Works
Orders.CustomerIDmust exist inCustomers.CustomerIDInsert Example
Adding Foreign Key to Existing Table
Cascade Options (Important)
You can control behavior on delete/update:
Options:
CASCADE→ delete/update child automaticallySET NULL→ set FK to NULLNO ACTION→ prevent operation (default)Check Foreign Keys in Database
Real-World Use Cases
Best Practices