🔍
Back

Explain joins in SQL with examples.

0 like 0 dislike

1 Answer

Of course. Here is a comprehensive explanation of SQL JOIN clauses, complete with their purpose, syntax, visual analogies, and practical examples.


What is a SQL JOIN?

A JOIN clause in SQL is used to combine rows from two or more tables based on a related column between them.

Databases are typically normalized, which means data is split into multiple, smaller tables to reduce redundancy and improve data integrity. For example, instead of storing customer information with every single order, you have a Customers table and an Orders table. JOINs are the essential tool for bringing this related, separated data back together in a meaningful way for queries and reports.

Sample Data for Examples

To demonstrate the different types of joins, we'll use two simple tables: Customers and Orders.

Customers Table:
| CustomerID | Name | City |
| :--- | :--- | :--- |
| 1 | Alice | New York |
| 2 | Bob | London |
| 3 | Charlie | Paris |

Orders Table:
| OrderID | CustomerID | OrderDate | Amount |
| :--- | :--- | :--- | :--- |
| 101 | 1 | 2023-01-15 | 150.00 |
| 102 | 2 | 2023-02-10 | 200.00 |
| 103 | 99 | 2023-02-18 | 50.00 |

Notice a few key things about our data:
Alice and Bob are in the Customers table and have placed orders in the Orders table.
Charlie is in the Customers table but has no orders.
* Order 103 is in the Orders table but has a CustomerID (99) that does not exist in the Customers table (this could be old or bad data).


Types of SQL JOINs

Here are the most common types of joins. We can visualize them using Venn diagrams, where each circle represents a table.

1. INNER JOIN
  • Purpose: Returns only the records that have matching values in both tables. This is the most common type of join.
  • Venn Diagram: The intersection (overlapping area) of the two circles.
  • Syntax:
    `sql
    SELECT columns
    FROM table1
    INNER JOIN table2 ON table1.common_column = table2.common_column;
    `
  • Example: Get a list of all orders with the corresponding customer names.

    `sql
    SELECT Customers.Name, Orders.OrderID, Orders.Amount
    FROM Customers
    INNER JOIN Orders ON Customers.CustomerID = Orders.CustomerID;
    `

  • Result:
    It only returns rows for Alice and Bob because they are the only customers with matching CustomerIDs in both tables. Charlie (no orders) and the orphan order (no customer) are excluded.
    | Name | OrderID | Amount |
    | :--- | :--- | :--- |
    | Alice | 101 | 150.00 |
    | Bob | 102 | 200.00 |
2. LEFT JOIN (or LEFT OUTER JOIN)
  • Purpose: Returns all records from the left table (the first one mentioned), and the matched records from the right table. If there is no match, the columns from the right table will contain NULL.
  • Venn Diagram: The entire left circle.
  • Syntax:
    `sql
    SELECT columns
    FROM table1
    LEFT JOIN table2 ON table1.common_column = table2.common_column;
    `
  • Example: Get a list of all customers and any orders they may have placed.

    `sql
    SELECT Customers.Name, Orders.OrderID, Orders.Amount
    FROM Customers
    LEFT JOIN Orders ON Customers.CustomerID = Orders.CustomerID;
    `

  • Result:
    This query returns all customers. Alice and Bob are matched with their orders. Charlie has no matching order, so the columns from the Orders table are NULL for him. This is useful for finding customers who haven't placed an order.
    | Name | OrderID | Amount |
    | :--- | :--- | :--- |
    | Alice | 101 | 150.00 |
    | Bob | 102 | 200.00 |
    | Charlie | NULL | NULL |
3. RIGHT JOIN (or RIGHT OUTER JOIN)
  • Purpose: Returns all records from the right table (the second one mentioned), and the matched records from the left table. If there is no match, the columns from the left table will contain NULL.
  • Venn Diagram: The entire right circle.
  • Syntax:
    `sql
    SELECT columns
    FROM table1
    RIGHT JOIN table2 ON table1.common_column = table2.common_column;
    `
  • Example: Get a list of all orders and the customer who placed them, if any.

    `sql
    SELECT Customers.Name, Orders.OrderID, Orders.Amount
    FROM Customers
    RIGHT JOIN Orders ON Customers.CustomerID = Orders.CustomerID;
    `

  • Result:
    This returns all orders. Orders 101 and 102 are matched with their customers. Order 103 has no matching customer, so the columns from the Customers table are NULL. This is useful for finding orders with invalid or missing customer data.
    | Name | OrderID | Amount |
    | :--- | :--- | :--- |
    | Alice | 101 | 150.00 |
    | Bob | 102 | 200.00 |
    | NULL | 103 | 50.00 |
4. FULL OUTER JOIN
  • Purpose: Returns all records when there is a match in either the left or the right table. It is essentially the combination of a LEFT JOIN and a RIGHT JOIN.
  • Venn Diagram: The entire area of both circles.
  • Syntax:
    `sql
    SELECT columns
    FROM table1
    FULL OUTER JOIN table2 ON table1.common_column = table2.common_column;
    `
  • Example: Get a complete list of all customers and all orders, linking them where possible.

    `sql
    SELECT Customers.Name, Orders.OrderID, Orders.Amount
    FROM Customers
    FULL OUTER JOIN Orders ON Customers.CustomerID = Orders.CustomerID;
    `

  • Result:
    This gives the most comprehensive list: matched records (Alice, Bob), unmatched records from the left (Charlie), and unmatched records from the right (Order 103).
    | Name | OrderID | Amount |
    | :--- | :--- | :--- |
    | Alice | 101 | 150.00 |
    | Bob | 102 | 200.00 |
    | Charlie | NULL | NULL |
    | NULL | 103 | 50.00 |
    (Note: MySQL does not have a FULL OUTER JOIN command. You can simulate it by combining a LEFT JOIN and a RIGHT JOIN with a UNION operator.)
5. CROSS JOIN
  • Purpose: Returns the Cartesian product of the two tables. This means it combines every row from the first table with every row from the second table. It does not use an ON clause.
  • Venn Diagram: Not applicable; it's a combinatorial product, not a set intersection.
  • Syntax:
    `sql
    SELECT columns
    FROM table1
    CROSS JOIN table2;
    `
  • Example: Match every customer with every possible order.

    `sql
    SELECT Customers.Name, Orders.OrderID
    FROM Customers
    CROSS JOIN Orders;
    `

  • Result:
    Since there are 3 customers and 3 orders, the result will have 3 * 3 = 9 rows. It's often used for generating test data or creating all possible combinations of items.
    | Name | OrderID |
    | :--- | :--- |
    | Alice | 101 |
    | Alice | 102 |
    | Alice | 103 |
    | Bob | 101 |
    | Bob | 102 |
    | Bob | 103 |
    | Charlie | 101 |
    | Charlie | 102 |
    | Charlie | 103 |
0 like 0 dislike
Next ⇨Next ⇨⇦ Previous⇦ Previous

Related questions

Explain exception handling in PL/SQL with example.
Answer : Of course. Here is a comprehensive explanation of exception handling in PL/SQL, complete with its purpose, structure, types of exceptions, and a detailed, practical example. --- ### What is Exception Handling? **Exception Handling** is a powerful ... ------------------------------------ ```...

Show More

Explain function in PL/SQL with example.
Answer : Of course. Here is a detailed explanation of functions in PL/SQL, including their purpose, syntax, a complete example, and a comparison with procedures. --- ### What is a PL/SQL Function? A **PL/SQL ... in `SELECT`, `WHERE`, `HAVING` clauses. | **Cannot** be used directly in SQL statements. |...

Show More

List the SQL operations and explain range searching operations between and pattern matching operator ‘like’ with example.
Answer : Of course. Here is a comprehensive overview of SQL operations, followed by a detailed explanation of the `BETWEEN` and `LIKE` operators with examples. --- ### List of SQL Operations (Categories) SQL ... alternative to using two separate comparisons with `AND` (e.g., `price >= 50 AND price ...

Show More

Explain PL/SQL block structure with the help of diagram.
Answer : Of course. Here is a detailed explanation of the PL/SQL block structure, complete with a diagram, a breakdown of its components, and a practical example. --- ### What is a ... exception. Control immediately jumps to the `EXCEPTION` section, and the corresponding error message is printed instead....

Show More

Write step by step syntax to create, open and close cursor in PL/SQL.
Answer : Of course. Here is a step-by-step guide to the syntax for creating, opening, fetching from, and closing a cursor in PL/SQL, complete with a full, practical example. --- ### Introduction: The Cursor Lifecycle Working ... END IF; DBMS_OUTPUT.PUT_LINE('An error occurred.'); END; / ```...

Show More
Welcome to Computer Engineering, where you can ask questions and receive answers from other members of the community.

Categories

...