How to create relationships between tables in SQL?

In SQL, tables can be linked together using foreign keys. A foreign key is a field in one table that contains the primary key of another table, establishing a relationship between the two tables.

To establish a relationship between tables, you first need to create a foreign key field in one table that references the primary key of another table. Then, associate the foreign key field with the primary key field to establish a relationship between the two tables.

For example, suppose there are two tables, one is the orders table and the other is the customers table. To establish a relationship between the orders table and the customers table, you can create a foreign key field in the orders table that references the primary key field in the customers table (such as customer ID). By linking the foreign key field in the orders table with the primary key field in the customers table, the relationship between the orders table and the customers table is established.

In SQL, creating relationships between tables can be done by using the ALTER TABLE statement to add foreign key constraints, for example:

ALTER TABLE orders
ADD CONSTRAINT fk_customer_id
FOREIGN KEY (customer_id) REFERENCES customers(id);

This creates a foreign key constraint in the order table, linking the customer_id field in the order table to the id field in the customer table, establishing a relationship between the order and customer tables.

bannerAds