Lesson 26: Why We Need Joins: Combining Multiple Tables
The fundamental purpose of relational databases is to store data without redundancy, typically by spreading information across many related tables.
The Need for Joins
If you want to know the name of the customer who placed a specific order, you need information from two tables:
- The
Orderstable (containsOrderIDand theCustomerIDForeign Key). - The
Customerstable (containsCustomerIDPrimary Key and theCustomerName).
A JOIN clause is used to combine rows from two or more tables based on a related column between them (usually the PK/FK pair).
Join Syntax Structure
While there are old ways of writing joins (using WHERE clause comparison), modern SQL uses the explicit JOIN syntax:
sql SELECT T1.column, T2.column FROM Table1 T1 -- Alias T1 JOIN Table2 T2 -- Alias T2 ON T1.ForeignKey = T2.PrimaryKey;
Table Aliases
Using short aliases (like T1 and T2 or C for Customers) is crucial, especially when columns in different tables share the same name (e.g., both tables might have an ID column).