What is a 'LEFT JOIN' in SQL?

Instruction: Explain the concept of a LEFT JOIN and provide an example query.

Context: This question tests the candidate's understanding of JOIN operations, focusing on the LEFT JOIN and its use in combining rows from two or more tables based on a related column.

Updated

Official answer

A left join keeps each left-side row. Every matching right-side row produces a result; if none match, the right-side columns are NULL. It does not guarantee one output row per left row when several right rows match.

This self-contained PostgreSQL example lists every customer and their paid orders:

WITH customers(id, name) AS (
  VALUES (1, 'Ari'), (2, 'Bo'), (3, 'Cy')
), orders(id, customer_id, status) AS (
  VALUES (100, 1, 'paid'), (101, 1, 'pending'), (102, 3, 'paid')
)
SELECT c.id AS customer_id, c.name, o.id AS order_id
FROM customers AS c
LEFT JOIN orders AS o
  ON o.customer_id = c.id AND o.status = 'paid'
ORDER BY c.id, o.id;

The output is (1, Ari, 100), (2, Bo, NULL), (3, Cy, 102). Moving o.status = 'paid' into a WHERE clause would remove the unmatched Bo row because the predicate would not be true for its NULL-extended order.

Follow-up: Add a second paid order for Ari. The result contains two Ari rows; aggregate deliberately if one row per customer is required.

Source

PostgreSQL: joined tables.

Related Questions