Given a table employees with columns id, name, department_id, and salary, which query returns the names of employees whose salary is greater than the average salary in their department?
SELECT name FROM employees WHERE salary > (SELECT AVG(salary) FROM employees WHERE department_id = employees.department_id);
Use a subquery to calculate the average salary for each employee's department.
Option A correctly uses a correlated subquery to compare each employee's salary to the average salary of their own department. Option A is invalid SQL syntax. Option A compares salary to the maximum salary, not average. Option A compares salary to the average salary of all employees, ignoring departments.
Given a table products with columns product_id, category_id, and price, which query lists all products with a price higher than every product in category 5?
SELECT product_id FROM products WHERE price > ALL (SELECT price FROM products WHERE category_id = 5);
Use ALL to ensure the price is greater than every price in category 5.
Option A correctly uses ALL to compare the price against all prices in category 5. Option A uses ANY, which means price greater than at least one, not all. Option A compares price to the maximum price, which is equivalent but less flexible if multiple max prices exist. Option A uses >= which includes equal prices, not strictly greater.
Which option contains a syntax error in the nested subquery?
SELECT name FROM employees WHERE department_id IN (SELECT department_id FROM departments WHERE location = 'NY');
Check if the subquery is properly enclosed in parentheses.
Option D is missing parentheses around the subquery, causing a syntax error. Options C and D are correct syntax. Option D is valid only if the subquery returns a single value; otherwise, it may cause runtime error but no syntax error.
Given the query below, which option optimizes it by reducing repeated subquery execution?
SELECT name FROM employees WHERE salary > (SELECT AVG(salary) FROM employees WHERE department_id = employees.department_id);
Use a common table expression (CTE) or join to avoid recalculating averages for each row.
Option C uses a CTE to calculate average salaries per department once, then joins to employees, improving performance. Option C compares salary to overall average, not per department. Options A and C misuse ALL/ANY with aggregates and produce incorrect results.
Which statement correctly describes the difference between correlated and non-correlated subqueries?
Think about whether the subquery uses columns from the outer query.
Correlated subqueries reference columns from the outer query and are evaluated for each row, while non-correlated subqueries are independent and run once. Option B reverses this. Option B is incorrect because correlated subqueries run multiple times. Option B is false; both types can appear in various clauses.