Preloader

Introduction to Table Relationships

SQL
SQL Tutorials

Table Relationships Introduction

In a database, table relationships connect data stored in different tables. Instead of putting everything in one table, we divide data into smaller tables and link them using keys.

For example:

users table

idname
1Rahul
2Sneha
3Amit

orders table

order_iduser_idamount
1011500
1021300
1032700

Here, users.id is a primary key and orders.user_id is a foreign key.
This creates a one to many relationship because one user can have many orders.

Now let’s understand different JOIN types using these tables.

1. INNER JOIN

INNER JOIN returns only matching records from both tables.

Query:

SELECT users.name, orders.order_id, orders.amount
FROM users
INNER JOIN orders
ON users.id = orders.user_id;

Result:

nameorder_idamount
Rahul101500
Rahul102300
Sneha103700

Amit is not shown because he has no orders.

2. LEFT JOIN

LEFT JOIN returns all records from the left table and matching records from the right table.

Query:

SELECT users.name, orders.order_id
FROM users
LEFT JOIN orders
ON users.id = orders.user_id;

Result:

nameorder_id
Rahul101
Rahul102
Sneha103
AmitNULL

Amit appears even though he has no orders.

3. RIGHT JOIN

RIGHT JOIN returns all records from the right table and matching records from the left table.

Query:

SELECT users.name, orders.order_id
FROM users
RIGHT JOIN orders
ON users.id = orders.user_id;

Result:

nameorder_id
Rahul101
Rahul102
Sneha103

Since all orders have valid users, the result looks like INNER JOIN in this case.

4. FULL JOIN

FULL JOIN returns all records from both tables. If there is no match, SQL fills the missing side with NULL.

Query:

SELECT users.name, orders.order_id
FROM users
FULL JOIN orders
ON users.id = orders.user_id;

Result:

Shows:

  • All users
  • All orders
  • NULL where no match exists

Note: MySQL does not directly support FULL JOIN.

5. SELF JOIN

SELF JOIN joins a table with itself.

Example: employees and managers in the same table.

employees table

idnamemanager_id
1RajNULL
2Meena1
3Arjun1

Query:

SELECT A.name AS Employee, B.name AS Manager
FROM employees A
LEFT JOIN employees B
ON A.manager_id = B.id;

Result:

EmployeeManager
RajNULL
MeenaRaj
ArjunRaj

6. CROSS JOIN

CROSS JOIN returns all possible combinations of rows.

Example Tables:

table1

id
1
2

table2

letter
A
B

Query:

SELECT *
FROM table1
CROSS JOIN table2;

Result:

idletter
1A
1B
2A
2B

It creates combinations of every row.

Summary

  • INNER JOIN → Only matching rows
  • LEFT JOIN → All left table rows
  • RIGHT JOIN → All right table rows
  • FULL JOIN → All rows from both tables
  • SELF JOIN → Table joined with itself
  • CROSS JOIN → All possible combinations

Understanding these JOIN types helps you combine data correctly and write strong SQL queries.

Check out our resources!

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *