A foreign key is a column or a set of columns in a table that establishes a relationship with the primary key or a unique key of another table. It acts as a cross-reference between two tables and enforces referential integrity between them.
Syntax:
CREATE TABLE table_name (
column1 datatype CONSTRAINT constraint_name,
column2 datatype,
...
FOREIGN KEY (foreign_key_column) REFERENCES referenced_table(referenced_column)
);
Example:
CREATE TABLE Orders (
order_id INT,
product VARCHAR(40),
total INT,
customer_id INT,
CONSTRAINT OrdersPK PRIMARY KEY (order_id),
FOREIGN KEY (customer_id) REFERENCES Customers(id)
);
Explanation:
-CREATE TABLE Orders: This line initiates the creation of a new table named Orders.
-( order_id INT, product VARCHAR(40), total INT, customer_id INT ): This section defines the structure of the Orders table. It consists of four columns:
order_id: An integer column to uniquely identify each order.
product: A variable-length string column with a maximum length of 40 characters, storing the name of the product.
total: An integer column to store the total amount for the order.
customer_id: An integer column to reference the customer associated with the order.
-CONSTRAINT OrdersPK PRIMARY KEY (order_id): This line defines a primary key constraint named OrdersPK on the order_id column. It ensures that each order_id value within the Orders table is unique.
-FOREIGN KEY (customer_id) REFERENCES Customers(id): This line establishes a foreign key constraint on the customer_id column of the Orders table, referencing the id column of the Customers table. This constraint ensures that every customer_id value in the Orders table must correspond to a valid id value in the Customers table, maintaining referential integrity between the two tables.