Complete the code to select all columns from a derived table named 'sub'.
SELECT [1] FROM (SELECT id, name FROM employees) AS sub;Using * selects all columns from the derived table sub.
Complete the code to calculate the average salary from a derived table named 'dept_salaries'.
SELECT AVG(salary) FROM (SELECT salary FROM employees WHERE department = [1]) AS dept_salaries;String literals in SQL must be enclosed in single quotes, so 'Sales' is correct.
Fix the error in the code by completing the alias for the derived table.
SELECT sales_summary.id, sales_summary.total FROM (SELECT id, SUM(amount) AS total FROM sales GROUP BY id) [1];AS without an alias name.In PostgreSQL, the alias for a derived table can be given without the AS keyword, so sales_summary alone is correct.
Fill both blanks to select employee names and their department names using a derived table.
SELECT e.name, d.[1] FROM employees e JOIN (SELECT id, [2] FROM departments) d ON e.department_id = d.id;
The derived table selects id and name from departments, aliased as d. The main query selects d.name as the department name.
Fill all three blanks to create a derived table that counts employees per department and select departments with more than 5 employees.
SELECT dept_name, emp_count FROM (SELECT d.name AS [1], COUNT(e.id) AS [2] FROM departments d LEFT JOIN employees e ON d.id = e.department_id GROUP BY d.name) AS dept_counts WHERE [3] > 5;
The derived table aliases d.name as dept_name and the count as emp_count. The WHERE clause filters rows where emp_count is greater than 5.