Home Python C Language C ++ HTML 5 CSS Javascript Java Kotlin SQL DJango Bootstrap React.js R C# PHP ASP.Net Numpy Dart Pandas Digital Marketing

FOREIGN KEY



SQL FOREIGN KEY Constraint


In SQL, a FOREIGN KEY constraint is a way to enforce referential integrity between two tables. It ensures that the values in a column (or columns) in one table match the values in a column (or columns) in another table's PRIMARY KEY or UNIQUE constraint.

Here's a basic example:

Suppose you have two tables: Orders and Customers. Each order is associated with a customer. You can enforce this relationship using a FOREIGN KEY constraint

        CREATE TABLE Customers (
            CustomerID INT PRIMARY KEY,
            CustomerName VARCHAR(255)
        );
        
        CREATE TABLE Orders (
            OrderID INT PRIMARY KEY,
            OrderDate DATE,
            CustomerID INT,
            FOREIGN KEY (CustomerID) REFERENCES Customers(CustomerID)
        );
      

In this example:

When using FOREIGN KEY constraints, it's important to note the following:

Foreign key constraints are a fundamental part of maintaining data integrity in relational databases, ensuring that relationships between tables remain consistent and valid.



Advertisement





Q3 Schools : India


Online Complier

HTML 5

Python

java

C++

C

JavaScript

Website Development

HTML

CSS

JavaScript

Python

SQL

Campus Learning

C

C#

java