What types of relationships between tables are used in SQL?
sobes.tech AI
Answer from AI
In SQL, there are several main types of relationships between tables that define how data from different tables are related:
-
One-to-One — each record in the first table corresponds to exactly one record in the second table. Used when data needs to be split into two tables, but the relationship is strictly 1:1.
-
One-to-Many — one record in the first table corresponds to many records in the second. For example, one user can have many orders.
-
Many-to-Many — records in the first table are related to many records in the second and vice versa. Implemented through an intermediate join table that contains foreign keys to both tables.
Example of a "one-to-many" relationship:
-- Users table
CREATE TABLE users (
id INT PRIMARY KEY,
name VARCHAR(100)
);
-- Orders table
CREATE TABLE orders (
id INT PRIMARY KEY,
user_id INT,
order_date DATE,
FOREIGN KEY (user_id) REFERENCES users(id)
);
Here, user_id in the orders table links an order to a specific user.