Which of the following best explains why subqueries are used to nest queries in SQL?
Think about how one query can depend on the result of another.
Subqueries nest queries so that the outer query can use the results of the inner query to filter or calculate data. This allows complex data retrieval in steps.
Given the tables employees(id, name, department_id) and departments(id, name), what is the output of this query?
SELECT name FROM employees WHERE department_id IN (SELECT id FROM departments WHERE name = 'Sales');
Look at how the inner query selects department IDs for Sales.
The subquery finds the IDs of departments named 'Sales'. The outer query then selects employees whose department_id matches those IDs, so it returns employees in Sales.
Which option correctly fixes the syntax error in this query?
SELECT name FROM employees WHERE department_id = (SELECT id FROM departments WHERE name = 'Sales' AND;
Check for incomplete conditions and missing parentheses.
The original query ends with an incomplete AND condition, causing syntax error. Option D completes the subquery properly with a closing parenthesis and no incomplete condition.
Which option is the best way to optimize this nested subquery for better performance?
SELECT name FROM employees WHERE department_id IN (SELECT id FROM departments WHERE name LIKE '%Sales%');
Think about how JOINs can be more efficient than IN with subqueries.
JOINs often perform better than IN with subqueries because the database can optimize the join operation better, especially with indexes.
Why does this query return no rows even though there are employees in the 'Marketing' department?
SELECT name FROM employees WHERE department_id = (SELECT id FROM departments WHERE name = 'Marketing');
Check if the subquery returns more than one value when using '='.
If the subquery returns multiple department IDs, using '=' causes an error or no results. Using IN instead of '=' fixes this.