Given an orders table, an order_items table, and a products table, write a query to find products that were never sold.
💡 Model Answer
Assuming the tables are defined as:
- products(product_id, name, ...)
- orders(order_id, ...)
- order_items(order_item_id, order_id, product_id, quantity, ...)
You can find products that never appear in any order_item record using a LEFT JOIN or NOT EXISTS. Example with LEFT JOIN:
SELECT p.product_id, p.name
FROM products p
LEFT JOIN order_items oi ON p.product_id = oi.product_id
WHERE oi.order_item_id IS NULL;
Alternatively, using NOT EXISTS:
SELECT p.product_id, p.name
FROM products p
WHERE NOT EXISTS (
SELECT 1 FROM order_items oi WHERE oi.product_id = p.product_id
);
Both queries return the same result. Complexity is O(P + OI) where P is the number of products and OI is the number of order_items, assuming appropriate indexes on product_id in order_items. The LEFT JOIN version may be slightly faster if the database can use an index on order_items.product_id to quickly find null matches.
This answer was generated by AI for study purposes. Use it as a starting point — personalize it with your own experience.
🎤 Get questions like this answered in real-time
Assisting AI listens to your interview, captures questions live, and gives you instant AI-powered answers on a discreet on-screen overlay.
Get Assisting AI — Starts at ₹500