Coding questions · Citadel
Implement Left Join Using Python Dictionaries Efficiently
This question evaluates competency in tabular data manipulation and join semantics using Python dictionaries, emphasizing understanding of hashing-based lookups and algorithmic complexity such as O(N+M).
Orders
+---------+----------+--------+
| order_id| customer | amount |
+---------+----------+--------+
| 101 | C1 | 250 |
| 102 | C2 | 300 |
| 103 | C3 | 150 |
Customers
+----------+-----------+
| customer | city |
+----------+-----------+
| C1 | Seattle |
| C3 | Boston |
| C4 | Austin |
Scenario
Performing a left join in pure Python without external libraries.
Question
Write Python code (no third-party packages) to left-join two lists of dictionaries on key "customer"; discuss an O(N+M) hashing solution.
Hints
Contrast nested loops with dict-based look-ups; handle missing matches gracefully.
Left Join Orders to Customers by Customer ID
You are given two tables: Orders and Customers. Write a SQL query to perform a LEFT JOIN from Orders to Customers on the "customer" key, returning all orders along with the customer's city when available. If a customer is missing from Customers, the city should be NULL.
Return columns: order_id, customer, amount, city.
Table orders
| column | type | constraints |
|---|---|---|
| order_id | INT | PRIMARY KEY |
| customer | VARCHAR(10) | NOT NULL |
| amount | INT | NOT NULL |
Sample data:
| amount | customer | order_id |
|---|---|---|
| 250 | C1 | 101 |
| 300 | C2 | 102 |
| 150 | C3 | 103 |
Table customers
| column | type | constraints |
|---|---|---|
| customer | VARCHAR(10) | PRIMARY KEY |
| city | VARCHAR(50) | NOT NULL |
Sample data:
| city | customer |
|---|---|
| Seattle | C1 |
| Boston | C3 |
| Austin | C4 |
Expected output
One row per order (all rows from orders), with city populated when the customer exists in customers; otherwise city is NULL.
| amount | city | customer | order_id |
|---|---|---|---|
| 250 | Seattle | C1 | 101 |
| 300 | NULL | C2 | 102 |
| 150 | Boston | C3 | 103 |
Hints
- Use a LEFT JOIN to keep all rows from orders.
- Join condition is orders.customer = customers.customer.
- Customers without a match should yield NULL for city.