[Solved] Products without a sale in the order table

EverSQL Database Performance Knowledge Base

Products without a sale in the order table

I'm trying to come up with a list of products without a sale, yet both tables are really long. At first my SQL I've been using but receiving timeout:"

SELECT products.product_id
FROM products
LEFT JOIN order_items USING (product_id)
WHERE order_items.product_id IS NULL

by using explain function before select:

Table       | Rows
Products    | 840,949
Order_Items | 688,499

It seems I'm not being efficient. Do you guys have any idea how to be more effective? Result I would like to achieve:

Product_ID
2323432
4565435
3453457

How to optimize this SQL query?

The following recommendations will help you in your SQL tuning process.
You'll find 3 sections below:

  1. Description of the steps you can take to speed up the query.
  2. The optimal indexes for this query, which you can copy and create in your database.
  3. An automatically re-written query you can copy and execute in your database.
The optimization process and recommendations:
  1. Create Optimal Indexes (modified query below): The recommended indexes are an integral part of this optimization effort and should be created before testing the execution duration of the optimized query.
Optimal indexes for this query:
ALTER TABLE `order_items` ADD INDEX `order_items_idx_product_id` (`product_id`);
The optimized query:
SELECT
        products.product_id 
    FROM
        products 
    LEFT JOIN
        order_items USING (product_id) 
    WHERE
        order_items.product_id IS NULL

Related Articles



* original question posted on StackOverflow here.