๐๐ป๐๐ฒ๐ฟ๐๐ถ๐ฒ๐๐ฒ๐ฟ:
You have 2 minutes to solve this SQL query.
Find the product(s) that have never been ordered.
Tables:
products(product_id, product_name)
order_details(order_id, product_id, quantity)
๐ ๐ฒ: Challenge accepted! ๐ช
SELECT
p.product_id,
p.product_name
FROM products p
LEFT JOIN order_details od
ON p.product_id = od.product_id
WHERE od.product_id IS NULL;
๐ก Explanation:
This query finds all products that do not have a matching record in the order_details table.
LEFT JOIN returns all products, regardless of whether they've been ordered. Products without matching orders will have NULL values for columns from order_details. WHERE od.product_id IS NULL filters only those products that have never been ordered.
This question tests your understanding of: LEFT JOIN, NULL handling, Finding unmatched records
๐ฏ Expected Output Example
Product ID Product Name
104 Wireless Mouse
118 USB Hub
125 Laptop Stand
๐ Alternative Using NOT EXISTS
SELECT
p.product_id,
p.product_name
FROM products p
WHERE NOT EXISTS (
SELECT 1
FROM order_details od
WHERE od.product_id = p.product_id
);
NOT EXISTS is often preferred because it handles NULL values correctly and can perform better than other approaches in many database systems.
๐ Tip for SQL Job Seekers:
Whenever you're asked to find records that don't exist in another table, consider these approaches:
LEFT JOIN ... IS NULL, NOT EXISTS โ
(often the best choice), NOT IN (be cautious with NULL values)
Knowing the pros and cons of each approach is a common interview discussion point.
โค๏ธ React with โค๏ธ for more SQL interview challenges!
Post #2927
4.37K
- โค 8