Core Module
12 min forge
SQL Joins: Combining Data
Inner, Left, Right, and Full Outer Joins explained with Venn diagrams.
SQL Joins: Combining Data
π What is it
Joins are used to combine rows from two or more tables based on a related column between them. Mastering joins is essential for almost any data-related interview.
ποΈ Types of Joins
- INNER JOIN: Returns records that have matching values in both tables.
- LEFT (OUTER) JOIN: Returns all records from the left table, and the matched records from the right table. (Unmatched right records result in
NULL). - RIGHT (OUTER) JOIN: Returns all records from the right table, and the matched records from the left table.
- FULL (OUTER) JOIN: Returns all records when there is a match in either left or right table.
- SELF JOIN: A regular join, but the table is joined with itself.
- CROSS JOIN: Returns the Cartesian product of the two tables.
β‘ LEFT JOIN vs INNER JOIN
INNER JOIN: Only returns users who HAVE made an order.LEFT JOIN: Returns ALL users, including those who HAVEN'T made an order (order details will beNULL).
π» Code example
sql StandardSELECT Users.Name, Orders.OrderDate FROM Users LEFT JOIN Orders ON Users.ID = Orders.UserID;
β Common mistakes
- Ambiguous Column Name: Forgetting to prefix columns with table names (e.g.,
Users.IDvsOrders.ID) when names overlap. - Join Condition: Forgetting the
ONclause or using the wrong column for joining. - Performance: Joining huge tables without indexes on the join columns.