Skip to content
Quantoros

Using orderitems: return pairs of productids that appear together in the same order, with how many orders they…

SQLLevel: IntermediateJoins and self-joins

Using order_items: return pairs of product_ids that appear together in the same order, with how many orders they co-occur in, most frequent first (break ties by the pair ids). Each pair once (a < b).

Table definitions (from the source exercise):

CREATE TABLE orders(order_id INTEGER PRIMARY KEY, customer_id INTEGER, order_date TEXT, amount REAL, rep_id INTEGER, discount REAL);
CREATE TABLE order_items(item_id INTEGER PRIMARY KEY, order_id INTEGER, product_id INTEGER, quantity INTEGER);
Hints
  • Define one output row and the source-table keys.
  • Check duplicates, NULLs and the order of filtering and aggregation.

Answer

Approach: Self-join order_items on order_id with a.product_id < b.product_id, then GROUP BY the pair.

SELECT a.product_id AS prod_a, b.product_id AS prod_b, COUNT(*) AS together
FROM order_items a
JOIN order_items b ON b.order_id = a.order_id
                  AND a.product_id < b.product_id
GROUP BY a.product_id, b.product_id
ORDER BY together DESC, prod_a, prod_b;

The source uses SQLite with a MySQL compatibility layer. Date and string functions are dialect dependent; the query is preserved as published.

Source and licence: SQL Practice Lab — Ebrahim Sharifi · MIT

Related questions