Complete the code to select employees whose salary is greater than the average salary in their department.
SELECT employee_id, salary FROM employees WHERE salary > (SELECT AVG(salary) FROM employees WHERE department_id = [1]);The subquery compares the department_id of the outer query with the department_id in the subquery. Using department_id correctly refers to the outer query's column in the correlated subquery.
Complete the code to find customers who have placed orders with amounts greater than the average order amount for that customer.
SELECT customer_id FROM orders o1 WHERE order_amount > (SELECT AVG(order_amount) FROM orders o2 WHERE o2.customer_id = [1]);o2 instead of the outer query alias.The subquery is correlated by matching o2.customer_id with the outer query's o1.customer_id. So, o1.customer_id is the correct reference.
Fix the error in the correlated subquery to correctly find products with price higher than the average price in their category.
SELECT product_id, price FROM products p WHERE price > (SELECT AVG(price) FROM products WHERE category_id = [1]);The subquery must correlate with the outer query's category_id using the alias p. So, p.category_id is correct.
Fill both blanks to select orders where the order amount is greater than the average order amount for the same customer.
SELECT order_id, order_amount FROM orders o WHERE order_amount > (SELECT AVG(order_amount) FROM orders [1] WHERE [2].customer_id = o.customer_id);
The subquery uses alias o2 and correlates with the outer query alias o by matching o2.customer_id to o.customer_id.
Fill all three blanks to select employees whose salary is above the average salary in their department and whose department is active.
SELECT e.employee_id, e.salary FROM employees e WHERE e.salary > (SELECT AVG(salary) FROM employees [1] WHERE [2].department_id = e.department_id) AND e.department_id IN (SELECT department_id FROM departments WHERE status = [3]);
The subquery uses alias emp to refer to employees and correlates with outer alias e. The department status must be 'active' to filter active departments.