SQL Joins
SQL JOIN
SQL JOIN is used to combine rows from two or more tables based on a related column between them. Joins are essential in relational databases where data is stored in multiple related tables.
Why Use JOIN?
In a relational database, information is often split into multiple tables to reduce duplication and improve structure.
- A customers table stores customer details
- An orders table stores order information
To see which customer placed which order, you need a JOIN.
Basic JOIN Syntax
SELECT columns FROM table1 JOIN table2 ON table1.column = table2.column;
Example: Customers and Orders
SELECT customers.name, orders.order_date FROM customers JOIN orders ON customers.id = orders.customer_id;
This query links customers to their orders using a common key.
Using Table Aliases with JOIN
SELECT c.name, o.order_date FROM customers AS c JOIN orders AS o ON c.id = o.customer_id;
Aliases make JOIN queries shorter and easier to read.
Common Types of JOIN
- INNER JOIN – returns matching rows from both tables
- LEFT JOIN – returns all rows from the left table and matched rows from the right table
- RIGHT JOIN – returns all rows from the right table and matched rows from the left table
- FULL JOIN – returns rows when there is a match in either table
- SELF JOIN – joins a table with itself
JOIN vs WHERE
Modern SQL uses JOIN with ON for linking tables. While older syntax used WHERE for joins, explicit JOIN syntax is clearer and recommended.
Foreign Keys
Joins usually connect a primary key in one table to a foreign key in another table.
Next Step
Continue with SQL INNER JOIN to understand the most commonly used join type.