Joins · Problem 53 of 118

Who Sent to Whom

HardJoinsBank data

For transfers 1 to 6, return transfer_id, the sender's full_name as sender, the receiver's full_name as receiver, and amount_cents. The sender owns the account in from_account, the receiver the one in to_account. Sort by transfer_id.

Hint 1

You need accounts twice (sending account, receiving account) and customers twice (sender, receiver). Use four different aliases.

Reference solution

SELECT t.transfer_id,
       cs.full_name AS sender,
       cr.full_name AS receiver,
       t.amount_cents
FROM transfers AS t
JOIN accounts AS fa ON fa.account_id = t.from_account
JOIN customers AS cs ON cs.customer_id = fa.customer_id
JOIN accounts AS ta ON ta.account_id = t.to_account
JOIN customers AS cr ON cr.customer_id = ta.customer_id
WHERE t.transfer_id BETWEEN 1 AND 6
ORDER BY t.transfer_id;

When a table is referenced twice by the same child row (a transfer has a from and a to account), join it twice under different aliases, once for each role. Read the query as a path: transfer, then the account that sent it, then that account's owner; transfer, then the account that received it, then its owner. Draw the path on paper first if it gets confusing.