DBMS & SQL · Intermediate · Topic 3 of 4
SQL: Subqueries & CTEs
5 questions.
Your progress0%
- 1st Visit
- 0/5
- 2nd Visit
- 0/5
- Revise
- 0/5
Overview
A subquery is a query inside another query. It can return one value, used in a comparison such as salary > (SELECT AVG(salary) ...), a list of values, used with IN or EXISTS, or a whole table in the FROM clause. A common table expression (CTE), written with WITH name AS (...), gives an intermediate result a name so that a multi-step query reads from top to bottom. Use these tools when a question needs a value computed from the data itself, such as "above the average", "the second highest" or "customers who never ordered". CTEs are available in MySQL 8.0 and later, PostgreSQL and SQL Server.
WITH dept_avg AS (
SELECT dept, AVG(salary) AS avg_sal
FROM employees
GROUP BY dept
)
SELECT e.name
FROM employees e
JOIN dept_avg d ON d.dept = e.dept
WHERE e.salary > d.avg_sal;
Questions
| # | Problem | Platform | Difficulty | Open | 1st1st Visit | 2nd2nd Visit | RevRevise |
|---|---|---|---|---|---|---|---|
| 1 | Customers Who Never Order | LeetCode | Easy | Solve Customers Who Never Order on LeetCode (opens in a new tab) | |||
| 2 | Second Highest Salary | LeetCode | Medium | Solve Second Highest Salary on LeetCode (opens in a new tab) | |||
| 3 | Department Highest Salary | LeetCode | Medium | Solve Department Highest Salary on LeetCode (opens in a new tab) | |||
| 4 | Customers Who Bought All Products | LeetCode | Medium | Solve Customers Who Bought All Products on LeetCode (opens in a new tab) | |||
| 5 | Investments in 2016 | LeetCode | Medium | Solve Investments in 2016 on LeetCode (opens in a new tab) |