Menu
CoddyTech

Join Two Tables

Part of the Fundamentals section of Coddy's PySpark journey. Lesson 12 of 18.

A join connects rows from two tables using a key. With orders.join(customers, "customer_id", "inner"), an order appears only when its key matches a customer. Naming a shared key as a string produces one copy of that key column.

matched = orders.join(customers, "customer_id", "inner")
matched.select("order_id", "name")

A left join keeps every left-hand row. When no right-hand row matches, its right-hand fields are null. If the right table has several matches for one key, the join produces several output rows. The customer keys in these exercises are unique.

For example, an order with customer key 4 gains the matching customer’s name from a lookup row with key 4. If an order’s key has no lookup row, an inner join removes it; a left join keeps it with a null name.

challenge icon

Challenge

Easy

The supplied customer lookup contains (1, "Ada") and (2, "Lin"), with columns customer_id, name. Join orders in df to that lookup using an inner join. Return order_id, name, amount. Exclude orders for unknown customers.

Write transform(df) and return a Spark DataFrame. The checker supplies df with schema order_id int, customer_id int, amount int. The session and F (PySpark functions) are already available. Do not print; the checker displays the returned rows. Return columns in this order: order_id, name, amount.

Try it yourself

def transform(df):
    customers = spark.createDataFrame([(1, "Ada"), (2, "Lin")], "customer_id int, name string")
    # Join df to customers and return the requested columns.
    return df
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals

Practice on your own: Online Python compiler