0
0
MySQLquery~5 mins

Why JOINs combine related tables in MySQL

Choose your learning style9 modes available
Introduction

JOINs let you bring together data from two or more tables that are connected. This helps you see related information in one place.

You want to see customer names with their orders.
You need to find products along with their supplier details.
You want to combine employee info with their department names.
You want to list students with their enrolled courses.
Syntax
MySQL
SELECT columns
FROM table1
JOIN table2 ON table1.common_column = table2.common_column;
The JOIN keyword connects rows from two tables based on a related column.
The ON clause specifies which columns link the tables.
Examples
This gets customer names with their order dates by matching customer IDs.
MySQL
SELECT customers.name, orders.order_date
FROM customers
JOIN orders ON customers.id = orders.customer_id;
This shows employees with their department names by linking department IDs.
MySQL
SELECT employees.name, departments.department_name
FROM employees
JOIN departments ON employees.department_id = departments.id;
Sample Program

This example creates two tables, adds data, and joins them to show customer names with their order dates.

MySQL
CREATE TABLE customers (id INT, name VARCHAR(20));
CREATE TABLE orders (id INT, customer_id INT, order_date DATE);

INSERT INTO customers VALUES (1, 'Alice'), (2, 'Bob');
INSERT INTO orders VALUES (101, 1, '2024-01-10'), (102, 2, '2024-01-11');

SELECT customers.name, orders.order_date
FROM customers
JOIN orders ON customers.id = orders.customer_id;
OutputSuccess
Important Notes

JOINs only show rows where the related columns match unless you use other JOIN types.

Always check that the columns you join on have matching data types.

Summary

JOINs combine rows from related tables using matching columns.

This helps you see connected data in one result.

Use the ON clause to specify how tables relate.