Sobes.tech
Junior — Middle

What are the ways tables in a database can be related to each other?

sobes.tech AI

Answer from AI

Tables in a database can be related to each other in several ways:

  1. Foreign Keys — the most common method. One table has a column that references the primary key of another table. This ensures data integrity and allows for joins.

  2. Many-to-many relationships — implemented through an intermediate (junction) table that contains foreign keys to both related tables.

  3. Hierarchical relationships — when a table references itself (for example, to represent a tree or hierarchy).

  4. Logical relationships without foreign keys — sometimes relationships are implemented at the application level, without explicit constraints in the database.

Example of a foreign key in SQL:

CREATE TABLE users (
    id INT PRIMARY KEY,
    name VARCHAR(100)
);

CREATE TABLE orders (
    id INT PRIMARY KEY,
    user_id INT,
    amount DECIMAL(10,2),
    FOREIGN KEY (user_id) REFERENCES users(id)
);

Here, the orders table is related to the users table through the foreign key user_id.