PostgreSQL JOINS
PostgreSQL JOINS
JOINS in PostgreSQL are used to combine rows from two or more tables based on a related column (usually a primary–foreign key relationship).
1️⃣ Why Use JOINS?
Example tables:
users
| id | name |
|---|---|
| 1 | Amit |
| 2 | Riya |
orders
| id | user_id | amount |
|---|---|---|
| 101 | 1 | 500 |
| 102 | 1 | 1200 |
| 103 | 2 | 700 |
To get user name with order amount, we use JOINs.
2️⃣ INNER JOIN
Returns only matching rows from both tables.
✔ Most commonly used JOIN.
3️⃣ LEFT JOIN (LEFT OUTER JOIN)
Returns all rows from left table and matching rows from right table.
If no match → NULL.
✔ Shows users even if they have no orders.
4️⃣ RIGHT JOIN (RIGHT OUTER JOIN)
Returns all rows from right table.
✔ Less common (can usually be rewritten as LEFT JOIN).
5️⃣ FULL JOIN (FULL OUTER JOIN)
Returns all rows from both tables.
✔ Includes unmatched rows from both sides.
6️⃣ CROSS JOIN
Returns Cartesian product (every row with every row).
❗ Use carefully — result size can explode.
7️⃣ SELF JOIN
A table joined with itself.
Example: employees with managers.
8️⃣ JOIN with WHERE vs ON
❗ Filtering JOIN condition in WHERE can change results.
9️⃣ JOIN Using USING Clause
When column names are same.
🔟 JOIN Multiple Tables
1️⃣1️⃣ Visual Summary
| JOIN Type | Result |
|---|---|
| INNER | Matching rows only |
| LEFT | All left + matching right |
| RIGHT | All right + matching left |
| FULL | All rows from both |
| CROSS | Every combination |
| SELF | Table joined with itself |
1️⃣2️⃣ Common JOIN Errors
❌ Missing ON condition
❌ Joining wrong columns
❌ Unexpected NULL values
❌ Huge result due to CROSS JOIN
1️⃣3️⃣ Best Practices
✔ Always specify JOIN condition
✔ Use table aliases
✔ Prefer LEFT JOIN over RIGHT JOIN
✔ Index foreign key columns
✔ Test with small datasets first
