liveBook · Manning

Join

As explained in Learn SQL in a Month of Lunches

A join is an SQL operation that combines rows from multiple tables according to a specified relationship or predicate.

A join combines related rows from separate tables in one query. It lets an order record lead to its customer, its purchased items, and each item’s title instead of storing all of that data in one oversized table. section 8.0 section 8.2.2

Write the first table after FROM, add JOIN for each related table, and use ON to state the matching columns. Qualify shared column names with their table names so SQL knows exactly which value you mean. section 8.2.1 section 8.2.2

Find the customer and item in an order

Start with orderheader, join customer through CustomerID, then join orderitem through OrderID. Add title only after orderitem, because orderitem supplies the TitleID that connects to title. Filter the selected order with WHERE. section 8.2.2

Keep joins readable:

  • Use explicit JOIN ... ON syntax rather than putting all table-matching predicates in WHERE; separating relationships from filters is easier to troubleshoot. section 8.4
  • Add as many joins as needed, but ensure both tables named in an ON condition have already been declared. section 8.2.2
  • Use the same matching relationship when filtering from either joined table; matching OrderID values can produce the same result either way. section 8.6

How Learn SQL in a Month of Lunches covers it

How deep it goes
Explains JOIN and ON through two- and four-table queries, while deferring more-inclusive join types.
Examples
Uses an order 1001 lookup, Chris Dixon’s orders, 2015 customers, and The Sum Also Rises purchases.
What it assumes
Builds from tables and relationships, then relies on primary and foreign key columns to choose matching values.
What you can do after
Apply it to write readable SQL queries that retrieve related data across several tables.
How it connects
Connects relational databases, primary keys, foreign keys, predicates, WHERE filtering, aliases, and INNER JOIN.

Also explained in

Compare how 16 books explain join →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn SQL in a Month of Lunches. The section links point to the parts of the book it draws on.