← All tasksSQL · Middle

Products that were never ordered

List products that don't appear in any order_items row: columns id and name, ordered by id. Note that product_id can be NULL (the product was deleted).

Tables

CREATE TABLE products (
  id   int PRIMARY KEY,
  name text NOT NULL
);

CREATE TABLE order_items (
  order_id   int NOT NULL,
  product_id int,  -- NULL: the product was deleted
  quantity   int NOT NULL
);

Tests (3)

Each test fills the tables with its own data and compares your query's result with the expected one: the same columns (names and order) and the same rows in the same order, so ORDER BY matters. The query runs in real PostgreSQL right in your browser; the first run downloads it (about 5 MB).

  1. INSERT INTO products VALUES (1, 'Mug'), (2, 'Tea'), (3, 'Pen');
    INSERT INTO order_items VALUES (100, 1, 2), (101, 1, 1);
  2. -- a NULL product_id: NOT IN returns nothing here
    INSERT INTO products VALUES (1, 'Mug'), (2, 'Tea'), (3, 'Pen');
    INSERT INTO order_items VALUES (100, 2, 1), (101, NULL, 1);
  3. -- every product was ordered
    INSERT INTO products VALUES (1, 'Mug');
    INSERT INTO order_items VALUES (100, 1, 1);