SQL Reference

Quick Reference

The FOREIGN KEY keywords are a key (a field or fields in one table that refers to the PRIMARY KEY in another table) used to link two tables together.

SQL FOREIGN KEY on CREATE TABLE

The following creates a FOREIGN KEY on the rep_id column when the Orders table is created.

MySQL:

CREATE TABLE Orders (
    order_id int NOT NULL,
    order_number int NOT NULL,
    rep_id int,
    PRIMARY KEY (order_id),
    FOREIGN KEY (rep_id) REFERENCES Persons(rep_id)
);

SQL Server:

CREATE TABLE Orders (
    order_id int NOT NULL PRIMARY KEY,
    order_number int NOT NULL,
    PersonID int FOREIGN KEY REFERENCES Persons(rep_id)
);

The following allows the naming of a FOREIGN KEY constraint, and defines a FOREIGN KEY constraint on multiple columns.

MySQL / SQL Server:

CREATE TABLE Orders (
    order_id int NOT NULL,
    order_number int NOT NULL,
    rep_id int,
    PRIMARY KEY (order_id),
    CONSTRAINT fk_order FOREIGN KEY (rep_id)
    REFERENCES Persons(rep_id)
);

SQL FOREIGN KEY on ALTER TABLE

The following creates a FOREIGN KEY constraint on the rep_id column when the Orders table already exists.

MySQL / SQL Server:

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

The following allows the naming of a FOREIGN KEY constraint, and defines a FOREIGN KEY constraint on multiple columns.

MySQL / SQL Server:

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

DROP a FOREIGN KEY CONSTRAINT

The following deletes the foreign key constraint named fk_customer_names from the Customers table.

MySQL:

ALTER TABLE Customers
DROP FOREIGN KEY fk_customer_names;

SQL Server:

ALTER TABLE Customers
DROP CONSTRAINT fk_customer_names;

SQL Notes:

  • Any work being done to modify the structure of a database or delete tables or the the database itself should only be done after making a recent backup

We’d like to acknowledge that we learned a great deal of our coding from W3Schools and TutorialsPoint, borrowing heavily from their teaching process and excellent code examples. We highly recommend both sites to deepen your experience, and further your coding journey. We’re just hitting the basics here at 1SMARTchicken.