Complete the code to select all customers who have placed at least one order.
SELECT customer_id FROM customers WHERE EXISTS (SELECT 1 FROM orders WHERE orders.customer_id = customers.[1]);
The subquery checks if there exists any order with the same customer_id as in the outer query. So, the correct column to compare is customer_id.
Complete the code to find products that have never been ordered.
SELECT product_id FROM products WHERE NOT EXISTS (SELECT 1 FROM order_items WHERE order_items.product_id = products.[1]);
The subquery checks if there exists any order item with the same product_id as in the outer query. To find products never ordered, we use NOT EXISTS and compare product_id.
Fix the error in the query to select employees who manage at least one department.
SELECT employee_id FROM employees WHERE EXISTS (SELECT 1 FROM departments WHERE departments.manager_id = employees.[1]);
manager_id from employees which may not exist.The subquery checks if the manager_id in departments matches the employee_id in employees. So, the correct column to compare in employees is employee_id.
Fill both blanks to select customers who have orders with total amount greater than 100.
SELECT customer_id FROM customers WHERE EXISTS (SELECT 1 FROM orders WHERE orders.customer_id = customers.[1] AND orders.[2] > 100);
The subquery checks for orders where the customer_id matches and the total_amount is greater than 100.
Fill all three blanks to select products that have been ordered more than 10 times in total.
SELECT product_id FROM products WHERE EXISTS (SELECT 1 FROM order_items WHERE order_items.product_id = products.[1] GROUP BY order_items.[2] HAVING SUM(order_items.[3]) > 10);
The subquery groups order items by product_id and sums the quantity ordered. It checks if the total quantity is greater than 10 for the product matching the outer query.