how to join two tables in sql
You join two tables in SQL by using a JOIN clause with a matching column
between them, usually a key such as id or customer_id.
What a JOIN Does
A JOIN combines rows from two tables into one result, based on a condition that tells SQL how the rows relate.
Example idea: match each order with the customer who placed it using
orders.customer_id = customers.id.
Basic INNER JOIN (most common)
This is the standard way to join two tables and return only matching rows.
sql
SELECT
c.id,
c.name,
o.order_id,
o.order_date
FROM customers AS c
INNER JOIN orders AS o
ON c.id = o.customer_id;
FROM customers AS c: start with the first table and optionally give it an alias.
INNER JOIN orders AS o: join the second table.
ON c.id = o.customer_id: join condition, telling SQL which rows match.
If a customer has no orders, that customer will not appear in this result.
Common JOIN Types (two tables)
All of these use the same basic pattern:
‘SELECT...FROMtable1SELECT...FROMtable1<join_type>JOINtable2ONcondition;‘SELECT...FROMtable1<jointype>JOINtable2ONcondition;‘
sql
SELECT ...
FROM table1
INNER JOIN table2 ON table1.key = table2.key; -- only matches
SELECT ...
FROM table1
LEFT JOIN table2 ON table1.key = table2.key; -- keep all from left
SELECT ...
FROM table1
RIGHT JOIN table2 ON table1.key = table2.key; -- keep all from right
SELECT ...
FROM table1
FULL JOIN table2 ON table1.key = table2.key; -- all rows both sides
Brief intuition:
- INNER JOIN : only rows where both tables match.
- LEFT JOIN : all rows from the left table, NULLs when no match on the right.
- RIGHT JOIN : all rows from the right table, NULLs when no match on the left.
- FULL JOIN : all rows from both tables, matching when possible, NULL otherwise.
HTML table: join types and behavior
| Join type | Keeps unmatched left rows? | Keeps unmatched right rows? | Typical use case |
|---|---|---|---|
| INNER JOIN | No | No | Only rows where both tables have related data (e.g., customers with at least one order). | [1][7]
| LEFT JOIN | Yes | No | Show all from main (left) table, with optional details from the second (e.g., all customers, even with no orders). | [8][5]
| RIGHT JOIN | No | Yes | Mirror of LEFT JOIN when the “main” table is on the right. | [5]
| FULL JOIN | Yes | Yes | See everything from both tables, matching where possible. | [7][5]
Step‑by‑step way to remember
- Pick the main table you care about most and put it after
FROM.
- Decide the relationship : do you only want matches (INNER) or also “no match” rows (LEFT/RIGHT/FULL)?
- Write the
JOINwith a clearONcondition using the key columns, for exampleON a.id = b.a_id.
- Select only the columns you need using table aliases like
a.colandb.col.
If you tell me your exact table names and key columns, I can show you the
precise JOIN query you’d use. Information gathered from public forums or
data available on the internet and portrayed here.