Consider the tables employees and departments. The employees table has columns id, name, salary, and department_id. The departments table has columns id and budget.
What will be the salary of employee with id = 3 after running this query?
UPDATE employees e SET salary = ( SELECT budget / 10 FROM departments d WHERE d.id = e.department_id ) WHERE e.id = 3;
Think about how the subquery uses the department_id of the employee to find the department's budget.
The subquery selects the budget from the departments table where the id matches the employee's department_id. Then it divides that budget by 10 and sets it as the new salary for the employee with id = 3.
Which statement best describes what happens when you run an UPDATE statement with a subquery in the SET clause?
Think about how the subquery can use values from the row being updated.
In an UPDATE with a correlated subquery, the subquery runs once per row, using that row's values to compute the new value.
Which option contains a syntax error in the UPDATE statement using a subquery?
UPDATE products p SET price = (SELECT AVG(price) FROM products WHERE category = p.category) WHERE category = 'Electronics';
Look carefully at the placement of parentheses and keywords.
Option B is missing parentheses around the subquery and has an extra WHERE clause outside the subquery, causing syntax error.
You want to update the salary of all employees to the average salary of their department. Which query is more efficient?
Consider how many times the subquery runs in each option.
Option D calculates average salaries per department once in a derived table, then joins to update, reducing repeated subquery executions.
Given the query below, why does it cause an error?
UPDATE orders o SET total = (SELECT SUM(amount) FROM order_items WHERE order_id = o.id) WHERE o.id IN (SELECT id FROM orders WHERE status = 'pending');
Think about whether the subquery returns a single value per row.
The subquery returns a single sum value per order, so it is valid. The WHERE clause limits updates to pending orders only.