SQL & Databases Masterclass Course
Welcome to the ultimate postgresql tutorial for beginners 2026. Work through interactive sql practice problems with solutions, master our comprehensive sql window functions tutorial modules, and prepare for tough sql interview questions at Google and Amazon entirely in your browser. Claim your course completion XP and build production-ready database mastery today!
SQL Subqueries: How to Write Nested Queries
Introduction & Core Concept
A Subquery (or nested query) is an independent inner SELECT statement embedded directly inside another query's WHERE, FROM, or SELECT layer.
SELECT * FROM employees
WHERE salary > (SELECT AVG(salary) FROM employees);This nested architectural pattern allows you to run analytical evaluations in stages—for instance, computing the global corporate benchmark average inside the inner subquery first, and then comparing individual employee rows against that dynamic benchmark in the outer parent layer.
Why & Where We Use It
Real-World Example
StaffCorp HR executives want a report identifying top-performing employees who earn strictly more than the average salary of their specific corporate department. They use a Correlated Subquery where the inner average calculation dynamically filters to match the outer employee's department ID.
Best Practices: What to Do & What NOT to Do
=, <, or >. If your subquery returns a list of multiple values, use IN.JOIN or Window Function can achieve the same result, as correlated subqueries execute repeatedly for every single outer row!Syntax & Pro Tips
SELECT name, salary FROM employees WHERE department_id IN (SELECT id FROM departments WHERE city = 'New York');