Module 3 · SQL: Getting Data Out of Databases · Lesson 10 of 51

Joining tables

Why data is split across tables, INNER, LEFT, RIGHT and FULL joins, join keys, finding unmatched rows, and the duplicate-row trap.

In this lesson · about 35 minutes

  • Explain why databases split data across tables
  • Choose between INNER and LEFT JOIN for a question
  • Find rows with no match, and avoid double-counting

Join syntax

SELECT m.name, o.order_id, o.total
FROM members AS m
LEFT JOIN app_orders AS o
  ON m.member_id = o.member_id;

AS m gives a table a short alias. ON says which columns must match: the join key.

JoinKeepsUse it for
INNEROnly rows that match on both sides"Orders with their member's details"
LEFTEvery left row; NULLs where there's no match"All members, and their orders if any"; finding members who never ordered
RIGHTEvery right rowRare: swap the tables and use LEFT
FULL OUTEREverything from bothReconciling two lists

Anti-join: to find members who never ordered, LEFT JOIN and keep the rows where the right side is NULL: WHERE o.order_id IS NULL.

Try it · data lab

Join two tables

Five loyalty members and six app orders. Switch the join type and see which rows survive, which get NULLs and which vanish.

members (left table)

#member_idnamehome_branch
01AmaraDowntown
12BilalCampus
23ChenRiverside
34DawitDowntown
45ElenaAirport

5 rows × 3 columns

app_orders (right table)

#order_idmember_idtotal
050118.5
150234.75
2503112
350423.25
450579
550636.5

6 rows × 3 columns

Rows in red have no partner in the other table.

Join type

SQL

SELECT m.member_id, m.name, o.order_id, o.total
FROM members AS m
INNER JOIN app_orders AS o
  ON m.member_id = o.member_id;

Result: 5 rows

#member_idnameorder_idtotal
01Amara5018.5
11Amara50312
22Bilal5043.25
33Chen5024.75
43Chen5066.5

5 rows × 4 columns

Only rows that match on both sides. Dawit and Elena (no app orders) and order 505 (member 7 isn't in the members table) disappear.

In pandas the same join is members.merge(app_orders, on="member_id", how="inner").

Joins in SQLite

Exercise

Members who never ordered

Return the name of every member with no app orders, sorted alphabetically. Use a LEFT JOIN and IS NULL.

Code that runs before yours
import sqlite3
import pandas as pd
con = sqlite3.connect(":memory:")
pd.read_csv("kc_orders.csv").to_sql("orders", con, index=False)
q = lambda sql: pd.read_sql_query(sql, con)
pd.DataFrame({"member_id": [1, 2, 3, 4, 5], "name": ["Amara", "Bilal", "Chen", "Dawit", "Elena"],
              "home_branch": ["Downtown", "Campus", "Riverside", "Downtown", "Airport"]}).to_sql("members", con, index=False)
pd.DataFrame({"order_id": [501, 502, 503, 504, 505, 506], "member_id": [1, 3, 1, 2, 7, 3],
              "total": [8.5, 4.75, 12.0, 3.25, 9.0, 6.5]}).to_sql("app_orders", con, index=False)

Exercise

App spend by home branch

Return each member home_branch and the total app spend of its members as spend, counting only matched orders (INNER JOIN). Sort by spend descending.

Code that runs before yours
import sqlite3
import pandas as pd
con = sqlite3.connect(":memory:")
pd.read_csv("kc_orders.csv").to_sql("orders", con, index=False)
q = lambda sql: pd.read_sql_query(sql, con)
pd.DataFrame({"member_id": [1, 2, 3, 4, 5], "name": ["Amara", "Bilal", "Chen", "Dawit", "Elena"],
              "home_branch": ["Downtown", "Campus", "Riverside", "Downtown", "Airport"]}).to_sql("members", con, index=False)
pd.DataFrame({"order_id": [501, 502, 503, 504, 505, 506], "member_id": [1, 3, 1, 2, 7, 3],
              "total": [8.5, 4.75, 12.0, 3.25, 9.0, 6.5]}).to_sql("app_orders", con, index=False)

Check your understanding0 of 3 correct

Question 1

1.You need every member, even those with no orders. Which join?

Question 2

2.Order 505 has member_id 7, who isn't in members. After an INNER JOIN, order 505…

Question 3

3.After joining members to orders, a member-level total doubles. Likely cause?

Quiz score: 0 of 3

Exercises solved: 0 of 2

Tip: answer every quiz question correctly first.

Written by Noviq Academy in its own words. Kettle & Crumb and all its data are made up for teaching; any resemblance to a real business is a coincidence. Python runs in your browser with Pyodide, so results can differ slightly from your own computer. Power BI, Tableau and other product names belong to their owners. Read-aloud uses your device's built-in voices.