Case 5: Basket analysis with a self join

People who buy running shoes often add socks. Pairs like that are worth money: as a bundle, as a recommendation on the product page or as the second product in an email. A self join on the order lines finds them for you.

In short: join order_items a to order_items b on the same order_id. With a.product_id < b.product_id each pair appears exactly once. When one side is fixed (a.product_id = 1), use <> and divide by the number of orders containing that product.

The situation

The e-commerce team wants two features: bundles with a small discount and a "frequently bought together" box on product pages. Before anyone builds guesses into the store, the orders should show which products people really buy together.

The data

order_items has one row per order line: order_id, product_id, quantity and unit_price. A product appears at most once per order, which the primary key on order_id and product_id guarantees. Names are in products. First, how many orders contain more than one product at all?

WITH per_order AS (
  SELECT order_id, COUNT(*) AS n
  FROM order_items
  GROUP BY order_id
)
SELECT n AS lines, COUNT(*) AS orders
FROM per_order
GROUP BY n;
linesorders
1189
242
38

Only 50 of the 239 orders have more than one product, and every pair comes from those 50 baskets. That is normal for a small store and a reason to read results based on a handful of orders with care.

Task 1: frequent product pairs

Task Which products often end up in the basket together? Show every product pair that appears together in at least 3 orders: product_1 and product_2 (the product names, the one with the lower product_id first) and orders (the number of orders containing the pair). Use all order items.

order_items 297 rows, 4 columns
order_idproduct_idquantityunit_price
500121119.9
50012219.9
50021189.9
50023124.9
50029124.9
50037149.9
50047149.9
50048119.9
50051189.9
50063124.9
50079124.9
50081189.9
50082114.9
50085134.9
50095134.9
50103124.9
501121119.9
50127149.9
50131189.9
50149124.9
50159124.9
501613179.9
50175134.9
50181189.9
50191189.9
50193124.9
502016199.9
502113179.9
502219129.9
50235134.9
50241189.9
50258119.9
502623139.9
502713179.9
50281189.9
502921119.9
50292219.9
503015127.9
50318119.9
503213179.9
50335134.9
50349124.9
50352214.9
503621119.9
50371829.9
50383124.9
50391189.9
50392214.9
50407149.9
50415134.9
50421189.9
50435134.9
50441189.9
50442114.9
504511129.9
5046171119
50471189.9
50481819.9
504921119.9
50501189.9
50511189.9
50524112.9
50539124.9
50545134.9
505516199.9
50564212.9
50578119.9
505816199.9
50595134.9
50602219.9
50613124.9
506213179.9
506311129.9
5064241129
50657149.9
50658119.9
506514116.9
50661189.9
50662214.9
506716199.9
50681189.9
50682214.9
50695134.9
50698119.9
50707149.9
507114116.9
50721189.9
50735134.9
50738119.9
507416199.9
50755134.9
50761189.9
50763124.9
50774112.9
507810159.9
507915127.9
508021119.9
50811189.9
50824212.9
508310147.92
50841171.92
50843119.92
508511123.92
508519123.92
50852017.92
508611123.92
508723131.92
508810147.92
508911123.92
50907139.92
509111123.92
50926110.32
50931171.92
50933119.92
509423131.92
5095241103.2
509613163.92
50975127.92
50982227.92
50992217.92
51005127.92
51006210.32
51015127.92
51016110.32
510223131.92
51036110.32
510316179.92
510421115.92
51052229.9
51061189.9
51069124.9
510711129.9
51087149.9
510819129.9
51082019.9
51091189.9
51092114.9
51105134.9
511110159.9
511213179.9
511314116.9
511421119.9
51151189.9
51166212.9
51171189.9
511821119.9
511910159.9
51201829.9
5121171119
51229124.9
512313179.9
51242019.9
51251189.9
51252114.9
51267149.9
512721119.9
51284112.9
512911129.9
513010159.9
51311189.9
51328119.9
513321119.9
51332219.9
513423139.9
513512144.9
513613179.9
513713179.9
513714116.9
513723139.9
51387149.9
51395134.9
51396112.9
514019129.9
514021119.9
51418119.9
51428119.9
51434112.9
51432219.9
51441189.9
51442114.9
51455134.9
514613179.9
514615127.9
51479124.9
51485134.9
51495134.9
51504212.9
51512219.9
5152171119
51533124.9
515419129.9
51557149.9
51561189.9
51564112.9
51573124.9
515811129.9
515913179.9
516011129.9
516111129.9
516219129.9
516312144.9
5164241129
51654212.9
516519129.9
51665134.9
51668119.9
51672114.9
51685134.9
5169241129
5170171119
51701839.9
51713124.9
517212144.9
51733124.9
5173241129
517416199.9
5175241129
51767149.9
517721119.9
51781189.9
51784112.9
51791189.9
51792214.9
51801839.9
51814112.9
518216199.9
5183241129
51843124.9
518516199.9
5186171119
518623139.9
51877149.9
51878119.9
518712144.9
518823139.9
518921119.9
51907149.9
5191171119
51911839.9
51925134.9
51935134.9
519413179.9
519514216.9
51968119.9
519715127.9
519816199.9
519919129.9
5200171119
52011189.9
52014112.9
52021189.9
52035134.9
52036112.9
520415127.9
520512144.9
520610159.9
520611129.9
52071189.9
52074112.9
520723139.9
520813179.9
520814216.9
520916199.9
52102214.9
521121119.9
52122214.9
52126112.9
521319129.9
52142214.9
52153124.9
52161189.9
521721119.9
521813179.9
521814116.9
52191189.9
522012144.9
52211189.9
52221189.9
52231189.9
52244212.9
52257149.9
52263124.9
522715127.9
522819129.9
52299124.9
52309124.9
52319124.9
52327149.9
52332114.9
52343124.9
52355134.9
52365134.9
523710159.9
523711129.9
52388119.9
52391189.9
52392114.9
products 24 rows, 5 columns
product_idnamecategorypriceunit_cost
1Running shoesRunning89.948
2Running socks, 3 pairsRunning14.95.2
3Running shirtRunning24.910.5
4Water bottle 750 mlAccessories12.94.1
5Yoga matFitness34.914
6Cork yoga blockFitness12.94.8
7Dumbbells, pairFitness49.922
8Resistance bands, set of 3Fitness19.96
9Foam rollerFitness24.99
10Bike helmetCycling59.927
11Bike light setCycling29.911.5
12Cycling jerseyCycling44.919
13Hiking backpack 30 lOutdoor79.936
14Hiking socksOutdoor16.96.1
15HeadlampOutdoor27.910.8
16Rain jacketOutdoor99.946
17Tennis racketBall sports11958
18Tennis balls, can of 4Ball sports9.93.4
19Training ball, size 5Ball sports29.911
20Ball pumpBall sports9.93
21Swim gogglesSwimming19.96.5
22Swim capSwimming9.92.6
23Sports bagAccessories39.915
24Heart rate watchAccessories12972

How it works

In a self join, the same table enters the query twice under different aliases. The condition b.order_id = a.order_id pairs every line with every line of the same order, including itself and in both directions. An order with running shoes and socks therefore produces four rows: shoes with shoes, shoes with socks, socks with shoes, socks with socks.

a.product_id < b.product_id keeps exactly one of them: shoes (1) with socks (2). An order with three products leaves three pairs. Then you group by both product IDs, count and use HAVING to keep pairs with at least three orders. The names come from two joins to products, one for each side.

Task 2: "frequently bought together"

Task The product page for the running shoes (product_id 1) is getting a "Frequently bought together" box. For every other product that was in the same order as the running shoes, show the name, the number of orders containing both, and the share as a percentage of all orders with running shoes (one decimal place).

order_items 297 rows, 4 columns
order_idproduct_idquantityunit_price
500121119.9
50012219.9
50021189.9
50023124.9
50029124.9
50037149.9
50047149.9
50048119.9
50051189.9
50063124.9
50079124.9
50081189.9
50082114.9
50085134.9
50095134.9
50103124.9
501121119.9
50127149.9
50131189.9
50149124.9
50159124.9
501613179.9
50175134.9
50181189.9
50191189.9
50193124.9
502016199.9
502113179.9
502219129.9
50235134.9
50241189.9
50258119.9
502623139.9
502713179.9
50281189.9
502921119.9
50292219.9
503015127.9
50318119.9
503213179.9
50335134.9
50349124.9
50352214.9
503621119.9
50371829.9
50383124.9
50391189.9
50392214.9
50407149.9
50415134.9
50421189.9
50435134.9
50441189.9
50442114.9
504511129.9
5046171119
50471189.9
50481819.9
504921119.9
50501189.9
50511189.9
50524112.9
50539124.9
50545134.9
505516199.9
50564212.9
50578119.9
505816199.9
50595134.9
50602219.9
50613124.9
506213179.9
506311129.9
5064241129
50657149.9
50658119.9
506514116.9
50661189.9
50662214.9
506716199.9
50681189.9
50682214.9
50695134.9
50698119.9
50707149.9
507114116.9
50721189.9
50735134.9
50738119.9
507416199.9
50755134.9
50761189.9
50763124.9
50774112.9
507810159.9
507915127.9
508021119.9
50811189.9
50824212.9
508310147.92
50841171.92
50843119.92
508511123.92
508519123.92
50852017.92
508611123.92
508723131.92
508810147.92
508911123.92
50907139.92
509111123.92
50926110.32
50931171.92
50933119.92
509423131.92
5095241103.2
509613163.92
50975127.92
50982227.92
50992217.92
51005127.92
51006210.32
51015127.92
51016110.32
510223131.92
51036110.32
510316179.92
510421115.92
51052229.9
51061189.9
51069124.9
510711129.9
51087149.9
510819129.9
51082019.9
51091189.9
51092114.9
51105134.9
511110159.9
511213179.9
511314116.9
511421119.9
51151189.9
51166212.9
51171189.9
511821119.9
511910159.9
51201829.9
5121171119
51229124.9
512313179.9
51242019.9
51251189.9
51252114.9
51267149.9
512721119.9
51284112.9
512911129.9
513010159.9
51311189.9
51328119.9
513321119.9
51332219.9
513423139.9
513512144.9
513613179.9
513713179.9
513714116.9
513723139.9
51387149.9
51395134.9
51396112.9
514019129.9
514021119.9
51418119.9
51428119.9
51434112.9
51432219.9
51441189.9
51442114.9
51455134.9
514613179.9
514615127.9
51479124.9
51485134.9
51495134.9
51504212.9
51512219.9
5152171119
51533124.9
515419129.9
51557149.9
51561189.9
51564112.9
51573124.9
515811129.9
515913179.9
516011129.9
516111129.9
516219129.9
516312144.9
5164241129
51654212.9
516519129.9
51665134.9
51668119.9
51672114.9
51685134.9
5169241129
5170171119
51701839.9
51713124.9
517212144.9
51733124.9
5173241129
517416199.9
5175241129
51767149.9
517721119.9
51781189.9
51784112.9
51791189.9
51792214.9
51801839.9
51814112.9
518216199.9
5183241129
51843124.9
518516199.9
5186171119
518623139.9
51877149.9
51878119.9
518712144.9
518823139.9
518921119.9
51907149.9
5191171119
51911839.9
51925134.9
51935134.9
519413179.9
519514216.9
51968119.9
519715127.9
519816199.9
519919129.9
5200171119
52011189.9
52014112.9
52021189.9
52035134.9
52036112.9
520415127.9
520512144.9
520610159.9
520611129.9
52071189.9
52074112.9
520723139.9
520813179.9
520814216.9
520916199.9
52102214.9
521121119.9
52122214.9
52126112.9
521319129.9
52142214.9
52153124.9
52161189.9
521721119.9
521813179.9
521814116.9
52191189.9
522012144.9
52211189.9
52221189.9
52231189.9
52244212.9
52257149.9
52263124.9
522715127.9
522819129.9
52299124.9
52309124.9
52319124.9
52327149.9
52332114.9
52343124.9
52355134.9
52365134.9
523710159.9
523711129.9
52388119.9
52391189.9
52392114.9
products 24 rows, 5 columns
product_idnamecategorypriceunit_cost
1Running shoesRunning89.948
2Running socks, 3 pairsRunning14.95.2
3Running shirtRunning24.910.5
4Water bottle 750 mlAccessories12.94.1
5Yoga matFitness34.914
6Cork yoga blockFitness12.94.8
7Dumbbells, pairFitness49.922
8Resistance bands, set of 3Fitness19.96
9Foam rollerFitness24.99
10Bike helmetCycling59.927
11Bike light setCycling29.911.5
12Cycling jerseyCycling44.919
13Hiking backpack 30 lOutdoor79.936
14Hiking socksOutdoor16.96.1
15HeadlampOutdoor27.910.8
16Rain jacketOutdoor99.946
17Tennis racketBall sports11958
18Tennis balls, can of 4Ball sports9.93.4
19Training ball, size 5Ball sports29.911
20Ball pumpBall sports9.93
21Swim gogglesSwimming19.96.5
22Swim capSwimming9.92.6
23Sports bagAccessories39.915
24Heart rate watchAccessories12972

This exercise is part of Premium.

Premium unlocks every exercise in every lesson, unlimited practice with fresh tasks and the final test with certificate.

See Premium Already Premium? Log in

The first exercise in this lesson is free.

How it works

Now one side is fixed: WHERE a.product_id = 1. Side b is every other product in the same orders. There is no second direction to remove, so <> is enough. For the share you need the number of orders with running shoes, which a subquery provides: (SELECT COUNT(*) FROM order_items WHERE product_id = 1). That is 40 orders, and 10 of them also contained running socks, so 25%.

In basket analysis this share is called confidence: how often is B in the basket when A is bought? Two more measures sit next to it. Support is the share of all orders that contain the pair. Lift divides confidence by B's overall share of orders. A lift above 1 means B is bought with A more often than it is bought in general.

Common mistakes

Not-equal instead of less-than for open pairs

With a.product_id <> b.product_id in task 1, every pair appears twice, once in each direction. The exercise says: "Your query returns 16 rows. Wanted: 8 rows."

Greater-than instead of less-than

With a.product_id > b.product_id the pairs are right, but the product with the higher ID comes first. The exercise reports that the columns are in the wrong order. What it means: the names in product_1 and product_2 have swapped places.

Not excluding the product itself

Without b.product_id <> a.product_id in task 2, the list recommends running shoes with running shoes at 100%: 7 rows instead of 6.

Dividing by the wrong total

Dividing by all order lines or all orders gives shares that are far too small. The question is: of the orders with running shoes, how many also contain this product?

Check your result

  • Task 1: 8 pairs. Running shoes and running socks lead with 10 orders, followed by running shoes and running shirt with 5.
  • Task 2: 6 products. Running socks 10 orders and 25%, running shirt 5 and 12.5%, water bottle 4 and 10%.
  • Cross-check: every number in task 2 has to match the count of the same pair in task 1, wherever that pair appears there.

In MySQL, PostgreSQL and SQL Server

Self joins, subqueries and HAVING work the same everywhere. Only the division needs care: in PostgreSQL and SQL Server, 100 * COUNT(*) / (SELECT COUNT(*) …) returns a whole number because both sides are integers. 100.0 prevents that in all four systems.

FAQ

How many orders does a basket analysis need?

The more, the more reliable. With 50 baskets, as here, strong pairs stand out. Pairs that share only two or three orders could be chance, which is why task 1 keeps pairs with at least three.

Does the query get slow with lots of order lines?

The self join creates, for each order, the square of its number of lines. As long as the join runs on order_id and that column is indexed, it stays manageable even for large tables. A self join without that condition would be a cross join.

Do cancelled orders count?

In this task they do, because the question is what customers put in the basket together. To look only at goods that were actually sold, also join orders and filter on the status.

Next up, case 6: customer lifetime value

In the last case you work out what a customer brings in during their first twelve months, on revenue and on gross margin, by acquisition channel.

Start case 6

Write to us

Choose language

Select your preferred language