FOREIGN KEY



FOREIGN KEY in SQL Server Database Table


A FOREIGN KEY is a key used to link two tables together.Sometimes this is also known as reference key


  • A FOREIGN KEY is a field (or collection of fields) in one table that refers to the PRIMARY KEY in another tab

  • The table containing the foreign key is called the child table, and the table containing the candidate key is called the referenced or parent table


    Example

    First table:

    PersonIDFirstNameLastNameAge
    1MATHURSUHAN25
    2DAKSHMAYUR26
    3ARJUNSINHA22

    Second table:

    OrderIDOrderNoPersonID
    17895642312
    26589742312
    39546872163
    48456321741

    Notice that the "PersonID" column in the "Second" table points to the "PersonID" column in the "First" table

    The "PersonID" column in the "First" table is the PRIMARY KEY in the "First" table.

    The "PersonID" column in the "Second" table is a FOREIGN KEY in the "Second" table.

    The FOREIGN KEY constraint is used to prevent actions that would destroy links between tables.

    SQL FOREIGN KEY on CREATE TABLE

    To create a foreign key on the "PersonID" column when the "Second" table is created:

    CREATE TABLE Orders (
        OrderID int NOT NULL PRIMARY KEY,
        OrderNumber int NOT NULL,
        PersonID int FOREIGN KEY REFERENCES Persons(PersonID)
    );
    
    SQL FOREIGN KEY on ALTER TABLE

    To create a FOREIGN KEY constraint on the "PersonID" column when the "Second" table is already created, use the following SQL

    ALTER TABLE Orders
    ADD FOREIGN KEY (PersonID) REFERENCES Persons(PersonID);
    

    To allow naming of a FOREIGN KEY constraint, and for defining a FOREIGN KEY constraint on multiple columns, use the following SQL syntax

    ALTER TABLE Orders
    ADD CONSTRAINT FK_PersonOrder
    FOREIGN KEY (PersonID) REFERENCES Persons(PersonID);
    
    DROP a FOREIGN KEY
    ALTER TABLE Orders
    DROP CONSTRAINT FK_PersonOrder;
    


    Connection String

    SQL Server Connection String Formats

    posted on 2019-08-27 05:53:53 - SQL Server Tutorials


    UNION

    union in SQL server

    posted on 2019-08-09 23:05:33 - SQL Server Tutorials


    System Functions

    System Functions in SQL Server

    posted on 2019-08-09 06:14:33 - SQL Server Tutorials


    Prompt Examples

    ChatGPT Prompt Examples

    posted on 2023-06-21 22:37:19 - ChatGPT Tutorials


    Use Cases

    Chat GPT Key Use Cases

    posted on 2023-06-21 21:03:17 - ChatGPT Tutorials


    Prompt Frameworks

    Prompt Frameworks

    posted on 2023-06-21 19:33:06 - ChatGPT Tutorials