sqlcmd.net validated sql reference
intermediate joining MySQL MariaDB SQL Server PostgreSQL SQLite

Fetch Rows Including Unmatched With LEFT JOIN

Return all rows from the left table and matching rows from the right, filling NULL where no match exists.

Docker-validated Not currently validation-green

Show all customers including those with no orders

Carol has no matching row in orders, so her total is NULL. Alice and Bob match normally. ORDER BY c.id keeps the result deterministic.

Rows loaded before the example query runs.
Setup
CREATE TABLE customers (id INT, name VARCHAR(50));

CREATE TABLE orders (id INT, customer_id INT, total INT);

INSERT INTO
  customers (id, name)
VALUES
  (1, 'Alice'),
  (2, 'Bob'),
  (3, 'Carol');

INSERT INTO
  orders (id, customer_id, total)
VALUES
  (1, 1, 99),
  (2, 2, 149);
Shared across supported engines.
SQL
SELECT
  c.name,
  o.total
FROM
  customers c
  LEFT JOIN orders o ON c.id = o.customer_id
ORDER BY
  c.id;
Returned rows for the shared example.
nametotal
Alice99
Bob149
CarolNULL

Output is identical across all engines.

Where this command helps.

  • showing all primary records even when related data is missing
  • finding unmatched rows on the right side of a relationship

What the command is doing.

LEFT JOIN keeps every row from the left table regardless of whether a matching row exists in the right table. Columns from the right table are NULL for unmatched rows. This is useful for finding missing relationships, such as customers who have never placed an order.