Loading lesson...
Getting tables to talk to each other
Getting tables to talk to each other
Topics covered: The Row Pairing Model, Join keys and data types, Primary and foreign keys, Cardinality, INNER JOIN
Before learning specific join syntax, you need to understand the fundamental concept: how SQL matches rows from different tables. A join creates pairs of rows from two tables. Each row from the first table is tested against each row from the second table. When rows match a condition, they form a pair in the output. This is the core mental model for understanding joins. SQL does not copy data or modify the original tables. It produces a new result set made of matched row pairs. Visual: How Pairs
The columns you choose to match on determine which rows get paired together. Selecting the right join keys is essential for correct results. The columns you use to match rows are called join keys. In the example above, customers.id and orders.cust_id are join keys. They contain the same kind of data: customer identifiers. For a join to work correctly, join keys must be comparable. This means they should have the same (or compatible) data types. Type Matching Matters If one column stores IDs as n
Professional databases follow consistent patterns for connecting tables. Learning these patterns helps you identify join columns quickly. Databases use a pattern called primary key / foreign key (PK/FK) to organize relationships between tables. Understanding this pattern helps you know which columns to join on. Primary Key A primary key uniquely identifies each row in a table. No two rows can have the same primary key value. Common examples: Foreign Key A foreign key is a column that references
How many rows match? This determines whether your result grows, shrinks, or stays the same size. Cardinality describes how many rows in one table match rows in another. Understanding cardinality helps you predict what your join results will look like. One-to-One (1:1) Each row in table A matches exactly one row in table B, and vice versa. Example: users and user_profiles tables Result: Same number of rows as each input table. One-to-Many (1:N) Each row in table A can match multiple rows in table
Syntax Example What INNER JOIN Excludes Writing Clean Joins Professional SQL requires clear, unambiguous code. Column qualification and table aliases make your joins readable and maintainable. Column Qualification When joining tables, both tables might have columns with the same name. SQL needs to know which table's column you mean. You specify this using table.column notation. The Problem This query is AMBIGUOUS if both tables have a "name" column: Error: Column "name" is ambiguous. SQL does no