HardSQL challenge #268SUBQUERYDATEANTI JOIN

Find Products with No Sales in the Last Month of Data

Return the products that were not sold in the final month of the order history.

The challenge runs on the SQLabHub practice database (SQLite) and uses the products, orders and order_items tables. You can solve it in the browser, with nothing to install.

Solve This SQL Challenge

Why this question comes up

The buying team wants to know which products sold nothing in the latest month, to decide whether to discount them or stop stocking them.

The task

Find products with no sales in the last month of the data, counting back from the most recent order date.

A correct answer returns 103 rows with 10 columns: id, name, category, price, cost, stock, sku, status, rating, review_count.

Tables used in this challenge

products 120 rows

id INTEGER (PK) · name TEXT · category TEXT · price REAL · cost REAL · stock INTEGER · sku TEXT · status TEXT · rating REAL · review_count INTEGER

First 3 rows of the products table
idnamecategorypricecoststockskustatusratingreview_count
1LEGO Creator Set 742pcsToys59.9919.8257SKU-000001activeNULL0
2Ergonomic Desk Mat XLOffice Supplies34.9910.85131SKU-000002active4.52
3Magnetic Phone Mount ProAutomotive24.999176SKU-000003active51

orders 200 rows

id INTEGER (PK) · user_id INTEGER · total REAL · discount REAL · item_count INTEGER · status TEXT · order_date TEXT · shipped_date TEXT · shipping_city TEXT · shipping_country TEXT

First 3 rows of the orders table
iduser_idtotaldiscountitem_countstatusorder_dateshipped_dateshipping_cityshipping_country
143321.680.259cancelled2024-04-24NULLDelhiIndia
2810.520.191delivered2024-03-152024-03-20ColumbusUSA
3136181.190.085delivered2023-02-152023-02-18ChicagoUSA

order_items 494 rows

id INTEGER (PK) · order_id INTEGER · product_id INTEGER · quantity INTEGER · unit_price REAL · subtotal REAL

First 3 rows of the order_items table
idorder_idproduct_idquantityunit_pricesubtotal
1176549.99249.95
2182332.9998.97
3165179.9979.99

The first rows of each table are shown. See how all the tables relate on the database schema page.

Expected output

Expected output of the challenge
idnamecategorypricecoststockskustatusratingreview_count
1LEGO Creator Set 742pcsToys59.9919.8257SKU-000001activeNULL0
2Ergonomic Desk Mat XLOffice Supplies34.9910.85131SKU-000002active4.52
4Sticky Notes Assorted 18pkOffice Supplies15.996.56164SKU-000004activeNULL0
5Vitamin D3+K2 180ctHealth & Beauty19.996183SKU-000005active42
6Complete Multivitamin 90ctHealth & Beauty24.998.75165SKU-000006active51

First 5 of 103 rows. This is the output of the model solution on the practice database. The task does not fix a sort order, so your rows may come back in a different order.

What you practise

  • Filtering rows with a WHERE condition
  • Testing whether a related row exists with EXISTS or NOT EXISTS
  • Summarising many rows into one value with COUNT, SUM, AVG, MIN or MAX
  • Combining rows from two tables on a matching key with an inner join
  • Writing a subquery that refers to the current row of the outer query
  • Using the result of one query inside another
  • Working with dates in SQLite: strftime, julianday and DATE

Hint and approach

Try the challenge first. Open these only when you need them.

Show the hint

NOT EXISTS with the product and the date condition inside the subquery

Show the step-by-step approach

How the model solution is built, in the order the database evaluates it:

  1. Read from the products table.
  2. Filter in WHERE: keep the rows where the subquery finds no matching row (NOT EXISTS).
  3. The subquery is correlated: it refers to the current outer row, so it is evaluated for each row. It works like this:
    1. Read from the order_items table.
    2. Join orders on order_items.order_id = orders.id.
    3. Filter in WHERE: keep the rows where order_items.product_id equals the outer row's id, and orders.order_date is at least DATE((SELECT MAX(order_date) FROM orders), '-1 month').
    4. The subquery runs once and returns a single value. It works like this:
      1. Read from the orders table.
      2. Aggregate over all the rows that are left: compute MAX(order_date). With no GROUP BY, the result is a single row.
    5. Select a constant: the enclosing query only needs to know whether a row exists, not what is in it.
  4. Return every column of products.
Show the model solution
SELECT p.* FROM products p WHERE NOT EXISTS ( SELECT 1 FROM order_items oi JOIN orders o ON oi.order_id = o.id WHERE oi.product_id = p.id AND o.order_date >= DATE((SELECT MAX(order_date) FROM orders), '-1 month') );

This query produced the expected output above. Yours does not have to match it word for word: any query that returns the same rows is correct.

What to watch for

The date condition has to sit inside the subquery. A LEFT JOIN with the date in the ON clause and a NULL test outside does not work here: it leaves one row per older order line rather than one row per product. NOT EXISTS answers the question once per product and returns each at most once.

  • EXISTS. The subquery must refer to the outer row. Without that link, EXISTS is simply true or false for the whole table and filters nothing.
  • Correlated subquery. A correlated subquery is evaluated per outer row, which gets slow on large tables. A join to a grouped subquery or a window function usually does the same work in one pass.
  • INNER JOIN. An inner join drops rows that have no partner on the other side, and it repeats a row once for every match, which inflates SUM and COUNT.

Another way to solve it

NOT IN gives the same products here because order_items.product_id is never NULL. If the subquery could return a NULL, NOT IN would return no rows at all, which is why NOT EXISTS is the safer habit.

Show the alternative query
SELECT p.*
FROM products p
WHERE p.id NOT IN (
  SELECT oi.product_id
  FROM order_items oi
  JOIN orders o ON oi.order_id = o.id
  WHERE o.order_date >= DATE((SELECT MAX(order_date) FROM orders), '-1 month')
);

Checked when this page was built: it returns the same rows as the model solution on the practice database.

Solve This SQL Challenge

Keep learning