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 be NULL).

πŸ’» Code example

sql Standard
SELECT 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.ID vs Orders.ID) when names overlap.
  • Join Condition: Forgetting the ON clause or using the wrong column for joining.
  • Performance: Joining huge tables without indexes on the join columns.