{"id":4003,"date":"2026-11-23T22:10:40","date_gmt":"2026-11-23T16:40:40","guid":{"rendered":"https:\/\/www.skillovilla.com\/blogs\/subqueries-in-sql"},"modified":"2026-11-23T22:11:05","modified_gmt":"2026-11-23T16:41:05","slug":"subqueries-in-sql","status":"publish","type":"post","link":"https:\/\/www.skillovilla.com\/blogs\/subqueries-in-sql","title":{"rendered":"Subqueries and Nested Queries in SQL, With Examples"},"content":{"rendered":"<p>A subquery, also called a nested query or inner query, is a SELECT written inside another SQL statement, in brackets. The database runs the inner query and hands its result to the outer one, so you can answer two-step questions in a single statement: &#8220;orders above the average order value&#8221; needs the average first, then the orders.<\/p>\n<p>Subqueries can sit in three places: in WHERE to filter, in FROM to act as a temporary table, and in SELECT to calculate a value per row. They also come in two kinds, plain and correlated, and the difference decides both what the query means and how fast it runs. This lesson covers each with worked examples on one dataset, plus the NOT IN trap that returns an empty result with no error.<\/p>\n<h2>Where a subquery can go<\/h2>\n<p>The table below shows each position, what the subquery must return there, and an example from the dataset used throughout this lesson.<\/p>\n<table>\n<thead>\n<tr>\n<th>Position<\/th>\n<th>What the subquery returns<\/th>\n<th>Syntax<\/th>\n<th>Example<\/th>\n<\/tr>\n<\/thead>\n<tbody>\n<tr>\n<td>WHERE, with a comparison<\/td>\n<td>One value (a scalar)<\/td>\n<td>WHERE col &gt; (SELECT &#8230;)<\/td>\n<td>WHERE amount &gt; (SELECT AVG(amount) FROM orders)<\/td>\n<\/tr>\n<tr>\n<td>WHERE, with IN<\/td>\n<td>One column, any number of rows<\/td>\n<td>WHERE col IN (SELECT col FROM &#8230;)<\/td>\n<td>WHERE customer_id IN (SELECT customer_id FROM orders WHERE amount &gt;= 900)<\/td>\n<\/tr>\n<tr>\n<td>WHERE, with EXISTS<\/td>\n<td>Any rows at all<\/td>\n<td>WHERE EXISTS (SELECT 1 FROM &#8230; WHERE &#8230;)<\/td>\n<td>WHERE NOT EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.customer_id)<\/td>\n<\/tr>\n<tr>\n<td>FROM (a derived table)<\/td>\n<td>A full table, which needs an alias<\/td>\n<td>FROM (SELECT &#8230;) AS alias<\/td>\n<td>FROM (SELECT customer_id, COUNT(*) AS order_count FROM orders GROUP BY customer_id) AS per_customer<\/td>\n<\/tr>\n<tr>\n<td>SELECT (a scalar subquery)<\/td>\n<td>One value per outer row<\/td>\n<td>SELECT col, (SELECT &#8230;) AS name<\/td>\n<td>SELECT name, (SELECT COUNT(*) FROM orders o WHERE o.customer_id = c.customer_id) AS orders<\/td>\n<\/tr>\n<tr>\n<td>HAVING<\/td>\n<td>One value<\/td>\n<td>HAVING SUM(col) &gt; (SELECT &#8230;)<\/td>\n<td>HAVING SUM(amount) &gt; (SELECT 2 * AVG(amount) FROM orders)<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<p>A scalar subquery that returns more than one row is an error (&#8220;subquery returns more than one row&#8221; in MySQL). If you get that, either the subquery needs an aggregate or the comparison needs IN.<\/p>\n<h2>The data used throughout<\/h2>\n<p>A Pune grocery delivery app, with five customers across the city and eight October orders. Order 4008 was a guest checkout, so its customer_id is NULL. Amounts are in rupees.<\/p>\n<table>\n<thead>\n<tr>\n<th>customer_id<\/th>\n<th>name<\/th>\n<th>area<\/th>\n<\/tr>\n<\/thead>\n<tbody>\n<tr>\n<td>C1<\/td>\n<td>Priya<\/td>\n<td>Kothrud<\/td>\n<\/tr>\n<tr>\n<td>C2<\/td>\n<td>Amit<\/td>\n<td>Baner<\/td>\n<\/tr>\n<tr>\n<td>C3<\/td>\n<td>Neha<\/td>\n<td>Hadapsar<\/td>\n<\/tr>\n<tr>\n<td>C4<\/td>\n<td>Vikram<\/td>\n<td>Wakad<\/td>\n<\/tr>\n<tr>\n<td>C5<\/td>\n<td>Sanjay<\/td>\n<td>Kothrud<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<table>\n<thead>\n<tr>\n<th>order_id<\/th>\n<th>customer_id<\/th>\n<th>order_date<\/th>\n<th>amount<\/th>\n<\/tr>\n<\/thead>\n<tbody>\n<tr>\n<td>4001<\/td>\n<td>C1<\/td>\n<td>2026-10-01<\/td>\n<td>640<\/td>\n<\/tr>\n<tr>\n<td>4002<\/td>\n<td>C2<\/td>\n<td>2026-10-01<\/td>\n<td>1250<\/td>\n<\/tr>\n<tr>\n<td>4003<\/td>\n<td>C1<\/td>\n<td>2026-10-04<\/td>\n<td>380<\/td>\n<\/tr>\n<tr>\n<td>4004<\/td>\n<td>C3<\/td>\n<td>2026-10-05<\/td>\n<td>910<\/td>\n<\/tr>\n<tr>\n<td>4005<\/td>\n<td>C4<\/td>\n<td>2026-10-09<\/td>\n<td>2100<\/td>\n<\/tr>\n<tr>\n<td>4006<\/td>\n<td>C1<\/td>\n<td>2026-10-12<\/td>\n<td>720<\/td>\n<\/tr>\n<tr>\n<td>4007<\/td>\n<td>C3<\/td>\n<td>2026-10-15<\/td>\n<td>300<\/td>\n<\/tr>\n<tr>\n<td>4008<\/td>\n<td>NULL<\/td>\n<td>2026-10-16<\/td>\n<td>560<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<h2>Example 1: orders above the average (subquery in WHERE)<\/h2>\n<p>You cannot write WHERE amount &gt; AVG(amount), because WHERE works one row at a time and has no average to compare against. A subquery computes the average first.<\/p>\n<table>\n<thead>\n<tr>\n<th>Part<\/th>\n<th>SQL<\/th>\n<\/tr>\n<\/thead>\n<tbody>\n<tr>\n<td>Outer query<\/td>\n<td>SELECT order_id, customer_id, amount FROM orders<\/td>\n<\/tr>\n<tr>\n<td>Subquery<\/td>\n<td>WHERE amount &gt; (SELECT AVG(amount) FROM orders)<\/td>\n<\/tr>\n<tr>\n<td>Sort<\/td>\n<td>ORDER BY amount DESC<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<p>The subquery returns 857.5, and the outer query keeps three orders:<\/p>\n<table>\n<thead>\n<tr>\n<th>order_id<\/th>\n<th>customer_id<\/th>\n<th>amount<\/th>\n<\/tr>\n<\/thead>\n<tbody>\n<tr>\n<td>4005<\/td>\n<td>C4<\/td>\n<td>2100<\/td>\n<\/tr>\n<tr>\n<td>4002<\/td>\n<td>C2<\/td>\n<td>1250<\/td>\n<\/tr>\n<tr>\n<td>4004<\/td>\n<td>C3<\/td>\n<td>910<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<p>The subquery runs once, and its result is treated as a constant. This is the simplest and most common kind.<\/p>\n<h2>Example 2: customers who placed a big order (IN)<\/h2>\n<p>Which customers have placed at least one order of 900 rupees or more? The subquery returns a list of customer IDs, and IN checks each customer against it.<\/p>\n<table>\n<thead>\n<tr>\n<th>Part<\/th>\n<th>SQL<\/th>\n<\/tr>\n<\/thead>\n<tbody>\n<tr>\n<td>Outer query<\/td>\n<td>SELECT name, area FROM customers<\/td>\n<\/tr>\n<tr>\n<td>Subquery<\/td>\n<td>WHERE customer_id IN (SELECT customer_id FROM orders WHERE amount &gt;= 900)<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<table>\n<thead>\n<tr>\n<th>name<\/th>\n<th>area<\/th>\n<\/tr>\n<\/thead>\n<tbody>\n<tr>\n<td>Amit<\/td>\n<td>Baner<\/td>\n<\/tr>\n<tr>\n<td>Neha<\/td>\n<td>Hadapsar<\/td>\n<\/tr>\n<tr>\n<td>Vikram<\/td>\n<td>Wakad<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<p>A join could answer this too, but a join would return Neha twice if she had two big orders, and you would need DISTINCT to fix it. IN asks a yes-or-no question per customer, so duplicates never appear.<\/p>\n<h2>Example 3: customers who never ordered, and the NOT IN trap<\/h2>\n<p>The natural way to find customers with no orders is NOT IN. Run it on this data and it returns nothing at all:<\/p>\n<table>\n<thead>\n<tr>\n<th>Query<\/th>\n<th>Result<\/th>\n<\/tr>\n<\/thead>\n<tbody>\n<tr>\n<td>SELECT name FROM customers WHERE customer_id NOT IN (SELECT customer_id FROM orders)<\/td>\n<td>No rows<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<p>Sanjay has never ordered, so why is he missing? The guest order 4008 puts a NULL into the subquery&#8217;s list. NOT IN means &#8220;not equal to every value in the list&#8221;, and comparing anything with NULL gives unknown, not true. One NULL in the list makes the whole condition unknown for every customer, and no rows come back. There is no error and no warning.<\/p>\n<p>NOT EXISTS does not have this problem, because it only asks whether a matching row exists:<\/p>\n<table>\n<thead>\n<tr>\n<th>Part<\/th>\n<th>SQL<\/th>\n<\/tr>\n<\/thead>\n<tbody>\n<tr>\n<td>Outer query<\/td>\n<td>SELECT name, area FROM customers c<\/td>\n<\/tr>\n<tr>\n<td>Correlated subquery<\/td>\n<td>WHERE NOT EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.customer_id)<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<table>\n<thead>\n<tr>\n<th>name<\/th>\n<th>area<\/th>\n<\/tr>\n<\/thead>\n<tbody>\n<tr>\n<td>Sanjay<\/td>\n<td>Kothrud<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<p>The rule worth memorising: for &#8220;not in another table&#8221;, use NOT EXISTS or a LEFT JOIN with WHERE &#8230; IS NULL. If you must use NOT IN, add WHERE customer_id IS NOT NULL inside the subquery. This is a favourite interview question precisely because the query looks correct.<\/p>\n<h2>Example 4: orders above that customer&#8217;s own average (correlated subquery)<\/h2>\n<p>A correlated subquery refers to a column from the outer query, so it cannot run once and be done. It runs again for every outer row, with that row&#8217;s values plugged in.<\/p>\n<p>The question: which orders were bigger than that same customer&#8217;s usual order?<\/p>\n<table>\n<thead>\n<tr>\n<th>Part<\/th>\n<th>SQL<\/th>\n<\/tr>\n<\/thead>\n<tbody>\n<tr>\n<td>Outer query<\/td>\n<td>SELECT order_id, customer_id, amount FROM orders o<\/td>\n<\/tr>\n<tr>\n<td>Correlated subquery<\/td>\n<td>WHERE amount &gt; (SELECT AVG(amount) FROM orders o2 WHERE o2.customer_id = o.customer_id)<\/td>\n<\/tr>\n<tr>\n<td>Sort<\/td>\n<td>ORDER BY order_id<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<p>For order 4001, the subquery averages C1&#8217;s orders (640, 380 and 720, average 580) and 640 passes. For 4004 it averages C3&#8217;s (910 and 300, average 605) and 910 passes.<\/p>\n<table>\n<thead>\n<tr>\n<th>order_id<\/th>\n<th>customer_id<\/th>\n<th>amount<\/th>\n<\/tr>\n<\/thead>\n<tbody>\n<tr>\n<td>4001<\/td>\n<td>C1<\/td>\n<td>640<\/td>\n<\/tr>\n<tr>\n<td>4004<\/td>\n<td>C3<\/td>\n<td>910<\/td>\n<\/tr>\n<tr>\n<td>4006<\/td>\n<td>C1<\/td>\n<td>720<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<p>C2 and C4 have one order each, which equals their own average, so neither passes. The guest order drops out too, because o2.customer_id = NULL is never true.<\/p>\n<p>Correlated subqueries are easy to write and can be slow on big tables, since the inner query conceptually runs once per row. Modern optimisers often rewrite them into joins, but on a 50-lakh-row table check the plan. The same question can be answered with AVG(amount) OVER (PARTITION BY customer_id), which our SQL window functions lesson covers.<\/p>\n<h2>Example 5: a subquery in FROM (a derived table)<\/h2>\n<p>Sometimes you need to aggregate twice: first per customer, then across customers. How many orders does a registered customer place on average, and what is the most anyone placed?<\/p>\n<table>\n<thead>\n<tr>\n<th>Part<\/th>\n<th>SQL<\/th>\n<\/tr>\n<\/thead>\n<tbody>\n<tr>\n<td>Outer query<\/td>\n<td>SELECT AVG(order_count) AS avg_orders_per_customer, MAX(order_count) AS most_orders<\/td>\n<\/tr>\n<tr>\n<td>Derived table<\/td>\n<td>FROM (SELECT customer_id, COUNT(*) AS order_count FROM orders WHERE customer_id IS NOT NULL GROUP BY customer_id) AS per_customer<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<table>\n<thead>\n<tr>\n<th>avg_orders_per_customer<\/th>\n<th>most_orders<\/th>\n<\/tr>\n<\/thead>\n<tbody>\n<tr>\n<td>1.75<\/td>\n<td>3<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<p>The inner query produces four rows (C1 with 3, C2 with 1, C3 with 2, C4 with 1), and the outer query treats them as a table. The alias per_customer is required in MySQL and SQL Server, and in PostgreSQL before version 16. Leaving it out is the most common derived-table error. One more SQL Server catch: AVG of a whole-number column returns a whole number there, so this query shows 1, not 1.75, unless you write AVG(order_count * 1.0).<\/p>\n<p>Once a derived table grows past a few lines, a CTE says the same thing more readably; our CTE in SQL lesson shows that rewrite.<\/p>\n<h2>Example 6: a subquery in SELECT<\/h2>\n<p>A scalar subquery in the SELECT list adds a calculated column per row. Here it builds a small customer summary, including customers with no orders:<\/p>\n<table>\n<thead>\n<tr>\n<th>Part<\/th>\n<th>SQL<\/th>\n<\/tr>\n<\/thead>\n<tbody>\n<tr>\n<td>Columns<\/td>\n<td>SELECT c.name, c.area,<\/td>\n<\/tr>\n<tr>\n<td>Order count<\/td>\n<td>(SELECT COUNT(*) FROM orders o WHERE o.customer_id = c.customer_id) AS orders,<\/td>\n<\/tr>\n<tr>\n<td>Last order<\/td>\n<td>(SELECT MAX(order_date) FROM orders o WHERE o.customer_id = c.customer_id) AS last_order<\/td>\n<\/tr>\n<tr>\n<td>Source<\/td>\n<td>FROM customers c<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<table>\n<thead>\n<tr>\n<th>name<\/th>\n<th>area<\/th>\n<th>orders<\/th>\n<th>last_order<\/th>\n<\/tr>\n<\/thead>\n<tbody>\n<tr>\n<td>Priya<\/td>\n<td>Kothrud<\/td>\n<td>3<\/td>\n<td>2026-10-12<\/td>\n<\/tr>\n<tr>\n<td>Amit<\/td>\n<td>Baner<\/td>\n<td>1<\/td>\n<td>2026-10-01<\/td>\n<\/tr>\n<tr>\n<td>Neha<\/td>\n<td>Hadapsar<\/td>\n<td>2<\/td>\n<td>2026-10-15<\/td>\n<\/tr>\n<tr>\n<td>Vikram<\/td>\n<td>Wakad<\/td>\n<td>1<\/td>\n<td>2026-10-09<\/td>\n<\/tr>\n<tr>\n<td>Sanjay<\/td>\n<td>Kothrud<\/td>\n<td>0<\/td>\n<td>NULL<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<p>This reads well, but each subquery is correlated and runs per customer. With two or three such columns on a large table, a LEFT JOIN to a grouped orders table is usually faster.<\/p>\n<h2>Nested more than one level: second highest and above-average spenders<\/h2>\n<p>Subqueries can contain subqueries. Two classics show up in interviews.<\/p>\n<p>The second highest order value: SELECT MAX(amount) FROM orders WHERE amount &lt; (SELECT MAX(amount) FROM orders). The inner query finds 2,100, and the outer one finds the largest amount below it, 1,250. This works for the second highest only; for the Nth, use DENSE_RANK.<\/p>\n<p>Customers whose total spend is more than twice the average order value, which nests three levels:<\/p>\n<table>\n<thead>\n<tr>\n<th>Level<\/th>\n<th>SQL<\/th>\n<\/tr>\n<\/thead>\n<tbody>\n<tr>\n<td>Outer<\/td>\n<td>SELECT name FROM customers WHERE customer_id IN (<\/td>\n<\/tr>\n<tr>\n<td>Middle<\/td>\n<td>SELECT customer_id FROM orders GROUP BY customer_id HAVING SUM(amount) &gt; (<\/td>\n<\/tr>\n<tr>\n<td>Inner<\/td>\n<td>SELECT AVG(amount) * 2 FROM orders))<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<p>The inner query gives 1,715. The middle one keeps customers who spent more than that: C1 at 1,740 and C4 at 2,100. The result is Priya and Vikram. Past three levels, rewrite it as a CTE. Nobody, including you next month, will read a five-deep nest correctly.<\/p>\n<h2>Subquery, join or CTE?<\/h2>\n<p>All three can often answer the same question. Pick by what the question is.<\/p>\n<table>\n<thead>\n<tr>\n<th>Situation<\/th>\n<th>Best fit<\/th>\n<th>Why<\/th>\n<\/tr>\n<\/thead>\n<tbody>\n<tr>\n<td>Compare with one aggregate (above average)<\/td>\n<td>Subquery in WHERE<\/td>\n<td>Short and clear<\/td>\n<\/tr>\n<tr>\n<td>&#8220;Has any&#8221; or &#8220;has none&#8221; in another table<\/td>\n<td>EXISTS or NOT EXISTS<\/td>\n<td>No duplicates, safe with NULLs<\/td>\n<\/tr>\n<tr>\n<td>Need columns from both tables in the output<\/td>\n<td>Join<\/td>\n<td>A subquery in WHERE cannot return columns<\/td>\n<\/tr>\n<tr>\n<td>Aggregate, then aggregate again<\/td>\n<td>Derived table or CTE<\/td>\n<td>CTE once it passes a few lines<\/td>\n<\/tr>\n<tr>\n<td>Same intermediate result used twice<\/td>\n<td>CTE<\/td>\n<td>Defined once, referenced twice<\/td>\n<\/tr>\n<tr>\n<td>Reused across many queries and reports<\/td>\n<td>View<\/td>\n<td>Saved in the database<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<p>On speed, an uncorrelated subquery and the equivalent join usually produce the same plan. The real differences are correctness (duplicates from joins, NULLs in NOT IN) and readability. Our <a href=\"https:\/\/www.skillovilla.com\/blogs\/sql-joins\">SQL joins guide<\/a> covers the join side with the same kind of examples.<\/p>\n<h2>Where MySQL, PostgreSQL and SQL Server differ<\/h2>\n<table>\n<thead>\n<tr>\n<th>Point<\/th>\n<th>MySQL<\/th>\n<th>PostgreSQL<\/th>\n<th>SQL Server<\/th>\n<\/tr>\n<\/thead>\n<tbody>\n<tr>\n<td>Alias on a derived table<\/td>\n<td>Required<\/td>\n<td>Required before version 16, optional from 16<\/td>\n<td>Required<\/td>\n<\/tr>\n<tr>\n<td>LIMIT inside an IN subquery<\/td>\n<td>Not supported<\/td>\n<td>Supported<\/td>\n<td>Use TOP; supported<\/td>\n<\/tr>\n<tr>\n<td>ORDER BY inside a subquery<\/td>\n<td>Allowed, usually ignored<\/td>\n<td>Allowed<\/td>\n<td>Error unless TOP or OFFSET is also used<\/td>\n<\/tr>\n<tr>\n<td>Subquery on the table being updated<\/td>\n<td>Error 1093 in UPDATE and DELETE; wrap it in a derived table<\/td>\n<td>Allowed<\/td>\n<td>Allowed<\/td>\n<\/tr>\n<tr>\n<td>ANY, ALL, EXISTS<\/td>\n<td>Supported<\/td>\n<td>Supported<\/td>\n<td>Supported<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<p>The MySQL 1093 error (&#8220;You can&#8217;t specify target table for update in FROM clause&#8221;) is the one that catches analysts cleaning data, and it is covered with the workaround in our lesson on deleting duplicate rows in SQL.<\/p>\n<h2>Mistakes people make with subqueries<\/h2>\n<p><strong>Using = where the subquery can return several rows.<\/strong> It works in testing when one row comes back and fails in production when two do. Use IN unless the subquery has an aggregate or a unique key filter.<\/p>\n<p><strong>NOT IN against a column with NULLs.<\/strong> Covered in Example 3. It is the most expensive mistake on this list, because the query runs and returns a plausible empty result.<\/p>\n<p><strong>Forgetting the derived table alias.<\/strong> Every subquery in FROM needs a name.<\/p>\n<p><strong>Nesting where a join or CTE would read better.<\/strong> If you cannot explain the query out loud from the outside in, restructure it.<\/p>\n<p><strong>Running correlated subqueries over millions of rows without checking the plan.<\/strong> Try the window function or join version and compare.<\/p>\n<p>Subqueries are a fixture of the intermediate round in analyst interviews; our <a href=\"https:\/\/www.skillovilla.com\/blogs\/sql-interview-questions\">SQL interview questions<\/a> include several, and the second-highest-salary pattern above is the single most asked.<\/p>\n<h2>Frequently asked questions<\/h2>\n<h3>What is a nested query in SQL?<\/h3>\n<p>A nested query, or subquery, is a SELECT statement placed inside another SQL statement, usually in brackets in the WHERE, FROM or SELECT clause. The inner query runs first and its result is used by the outer query. It lets you answer questions that need an intermediate result, such as finding orders above the average order value.<\/p>\n<h3>What is a correlated subquery?<\/h3>\n<p>A correlated subquery refers to a column of the outer query, so its result changes for each outer row and it is evaluated once per row. An example is comparing each order with the average of that same customer&#8217;s orders. A plain subquery, by contrast, does not depend on the outer query and runs once.<\/p>\n<h3>What is the difference between a subquery and a join?<\/h3>\n<p>A join combines rows from two tables side by side, so you can return columns from both. A subquery in WHERE only filters the outer table and does not add columns. Joins can create duplicate rows when one side matches several times, while IN and EXISTS subqueries never do. Performance is usually similar.<\/p>\n<h3>Why does NOT IN return no rows?<\/h3>\n<p>If the subquery&#8217;s result contains even one NULL, NOT IN returns no rows, because comparing a value with NULL gives unknown rather than true. Use NOT EXISTS instead, or add a WHERE column IS NOT NULL filter inside the subquery. This is one of the most common silent errors in SQL.<\/p>\n<h3>What is the difference between IN and EXISTS?<\/h3>\n<p>IN compares a value against the list the subquery returns. EXISTS checks only whether the subquery returns any row, and it is usually written as a correlated subquery. For positive checks they give the same result and similar performance. For negative checks, NOT EXISTS is safer because NOT IN breaks when the list contains a NULL.<\/p>\n<h3>How many levels can subqueries be nested?<\/h3>\n<p>Databases allow far more than you should use. SQL Server allows up to 32 levels and MySQL and PostgreSQL have no small practical limit. Readability is the real limit: beyond two or three levels, rewrite the query with CTEs so each step has a name.<\/p>\n<h2>Practise the questions that need two steps<\/h2>\n<p>Most analyst questions that sound simple, such as customers who never ordered or orders above a customer&#8217;s own average, need a subquery or something equivalent. Writing them correctly the first time, and spotting the NULL that empties a result, comes from practice with feedback.<\/p>\n<p>SkilloVilla&#8217;s <a href=\"https:\/\/www.skillovilla.com\/courses\/sql-beginner-to-advanced\">SQL: Beginner to Advanced course<\/a> covers the fundamental statements, conditional functions, aggregation, joins and advanced SQL statements, taught in live classes with mentor support and practice on SQL playgrounds. If you want SQL as part of a full analyst programme with Python, Power BI and placement support, see the <a href=\"https:\/\/www.skillovilla.com\/tracks\/data-analytics-python\">Data Analytics with Python track<\/a>.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Nested queries in SQL explained: subqueries in WHERE, FROM and SELECT, correlated subqueries, EXISTS vs IN, and the NOT IN NULL trap, with examples.<\/p>\n","protected":false},"author":27,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"om_disable_all_campaigns":false,"_monsterinsights_skip_tracking":false,"_monsterinsights_sitenote_active":false,"_monsterinsights_sitenote_note":"","_monsterinsights_sitenote_category":0,"footnotes":""},"categories":[200],"tags":[],"class_list":["post-4003","post","type-post","status-publish","format-standard","hentry","category-data-analytics"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v23.1 - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>Subqueries and Nested Queries in SQL, With Examples<\/title>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/www.skillovilla.com\/blogs\/subqueries-in-sql\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Subqueries and Nested Queries in SQL, With Examples\" \/>\n<meta property=\"og:description\" content=\"Nested queries in SQL explained: subqueries in WHERE, FROM and SELECT, correlated subqueries, EXISTS vs IN, and the NOT IN NULL trap, with examples.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/www.skillovilla.com\/blogs\/subqueries-in-sql\" \/>\n<meta property=\"og:site_name\" content=\"SkilloVilla\" \/>\n<meta property=\"article:published_time\" content=\"2026-11-23T16:40:40+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2026-11-23T16:41:05+00:00\" \/>\n<meta name=\"author\" content=\"SkilloVilla Team\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"SkilloVilla Team\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"11 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"Article\",\"@id\":\"https:\/\/www.skillovilla.com\/blogs\/subqueries-in-sql#article\",\"isPartOf\":{\"@id\":\"https:\/\/www.skillovilla.com\/blogs\/subqueries-in-sql\"},\"author\":{\"name\":\"SkilloVilla Team\",\"@id\":\"https:\/\/www.skillovilla.com\/blogs\/#\/schema\/person\/f64a2675b6d238b7e44744a87e5c4943\"},\"headline\":\"Subqueries and Nested Queries in SQL, With Examples\",\"datePublished\":\"2026-11-23T16:40:40+00:00\",\"dateModified\":\"2026-11-23T16:41:05+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\/\/www.skillovilla.com\/blogs\/subqueries-in-sql\"},\"wordCount\":2427,\"commentCount\":0,\"publisher\":{\"@id\":\"https:\/\/www.skillovilla.com\/blogs\/#organization\"},\"articleSection\":[\"Data analytics\"],\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"CommentAction\",\"name\":\"Comment\",\"target\":[\"https:\/\/www.skillovilla.com\/blogs\/subqueries-in-sql#respond\"]}]},{\"@type\":\"WebPage\",\"@id\":\"https:\/\/www.skillovilla.com\/blogs\/subqueries-in-sql\",\"url\":\"https:\/\/www.skillovilla.com\/blogs\/subqueries-in-sql\",\"name\":\"Subqueries and Nested Queries in SQL, With Examples\",\"isPartOf\":{\"@id\":\"https:\/\/www.skillovilla.com\/blogs\/#website\"},\"datePublished\":\"2026-11-23T16:40:40+00:00\",\"dateModified\":\"2026-11-23T16:41:05+00:00\",\"breadcrumb\":{\"@id\":\"https:\/\/www.skillovilla.com\/blogs\/subqueries-in-sql#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/www.skillovilla.com\/blogs\/subqueries-in-sql\"]}]},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/www.skillovilla.com\/blogs\/subqueries-in-sql#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\/\/www.skillovilla.com\/blogs\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Subqueries and Nested Queries in SQL, With Examples\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\/\/www.skillovilla.com\/blogs\/#website\",\"url\":\"https:\/\/www.skillovilla.com\/blogs\/\",\"name\":\"SkilloVilla\",\"description\":\"Data careers, taught live\",\"publisher\":{\"@id\":\"https:\/\/www.skillovilla.com\/blogs\/#organization\"},\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\/\/www.skillovilla.com\/blogs\/?s={search_term_string}\"},\"query-input\":\"required name=search_term_string\"}],\"inLanguage\":\"en-US\"},{\"@type\":\"Organization\",\"@id\":\"https:\/\/www.skillovilla.com\/blogs\/#organization\",\"name\":\"SkilloVilla\",\"url\":\"https:\/\/www.skillovilla.com\/blogs\/\",\"logo\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/www.skillovilla.com\/blogs\/#\/schema\/logo\/image\/\",\"url\":\"https:\/\/www.skillovilla.com\/blogs\/wp-content\/uploads\/2021\/07\/logo-thumbnail.png\",\"contentUrl\":\"https:\/\/www.skillovilla.com\/blogs\/wp-content\/uploads\/2021\/07\/logo-thumbnail.png\",\"width\":1200,\"height\":627,\"caption\":\"SkilloVilla\"},\"image\":{\"@id\":\"https:\/\/www.skillovilla.com\/blogs\/#\/schema\/logo\/image\/\"}},{\"@type\":\"Person\",\"@id\":\"https:\/\/www.skillovilla.com\/blogs\/#\/schema\/person\/f64a2675b6d238b7e44744a87e5c4943\",\"name\":\"SkilloVilla Team\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/www.skillovilla.com\/blogs\/#\/schema\/person\/image\/\",\"url\":\"https:\/\/secure.gravatar.com\/avatar\/5e0b6f9e8405f5d6fc302700051e351ffa38fb1cf2709a0cb4e96b5622c497d0?s=96&d=mm&r=g\",\"contentUrl\":\"https:\/\/secure.gravatar.com\/avatar\/5e0b6f9e8405f5d6fc302700051e351ffa38fb1cf2709a0cb4e96b5622c497d0?s=96&d=mm&r=g\",\"caption\":\"SkilloVilla Team\"},\"url\":\"https:\/\/www.skillovilla.com\/blogs\/author\/sankalp_agarwal\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Subqueries and Nested Queries in SQL, With Examples","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/www.skillovilla.com\/blogs\/subqueries-in-sql","og_locale":"en_US","og_type":"article","og_title":"Subqueries and Nested Queries in SQL, With Examples","og_description":"Nested queries in SQL explained: subqueries in WHERE, FROM and SELECT, correlated subqueries, EXISTS vs IN, and the NOT IN NULL trap, with examples.","og_url":"https:\/\/www.skillovilla.com\/blogs\/subqueries-in-sql","og_site_name":"SkilloVilla","article_published_time":"2026-11-23T16:40:40+00:00","article_modified_time":"2026-11-23T16:41:05+00:00","author":"SkilloVilla Team","twitter_card":"summary_large_image","twitter_misc":{"Written by":"SkilloVilla Team","Est. reading time":"11 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/www.skillovilla.com\/blogs\/subqueries-in-sql#article","isPartOf":{"@id":"https:\/\/www.skillovilla.com\/blogs\/subqueries-in-sql"},"author":{"name":"SkilloVilla Team","@id":"https:\/\/www.skillovilla.com\/blogs\/#\/schema\/person\/f64a2675b6d238b7e44744a87e5c4943"},"headline":"Subqueries and Nested Queries in SQL, With Examples","datePublished":"2026-11-23T16:40:40+00:00","dateModified":"2026-11-23T16:41:05+00:00","mainEntityOfPage":{"@id":"https:\/\/www.skillovilla.com\/blogs\/subqueries-in-sql"},"wordCount":2427,"commentCount":0,"publisher":{"@id":"https:\/\/www.skillovilla.com\/blogs\/#organization"},"articleSection":["Data analytics"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/www.skillovilla.com\/blogs\/subqueries-in-sql#respond"]}]},{"@type":"WebPage","@id":"https:\/\/www.skillovilla.com\/blogs\/subqueries-in-sql","url":"https:\/\/www.skillovilla.com\/blogs\/subqueries-in-sql","name":"Subqueries and Nested Queries in SQL, With Examples","isPartOf":{"@id":"https:\/\/www.skillovilla.com\/blogs\/#website"},"datePublished":"2026-11-23T16:40:40+00:00","dateModified":"2026-11-23T16:41:05+00:00","breadcrumb":{"@id":"https:\/\/www.skillovilla.com\/blogs\/subqueries-in-sql#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/www.skillovilla.com\/blogs\/subqueries-in-sql"]}]},{"@type":"BreadcrumbList","@id":"https:\/\/www.skillovilla.com\/blogs\/subqueries-in-sql#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/www.skillovilla.com\/blogs"},{"@type":"ListItem","position":2,"name":"Subqueries and Nested Queries in SQL, With Examples"}]},{"@type":"WebSite","@id":"https:\/\/www.skillovilla.com\/blogs\/#website","url":"https:\/\/www.skillovilla.com\/blogs\/","name":"SkilloVilla","description":"Data careers, taught live","publisher":{"@id":"https:\/\/www.skillovilla.com\/blogs\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/www.skillovilla.com\/blogs\/?s={search_term_string}"},"query-input":"required name=search_term_string"}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/www.skillovilla.com\/blogs\/#organization","name":"SkilloVilla","url":"https:\/\/www.skillovilla.com\/blogs\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/www.skillovilla.com\/blogs\/#\/schema\/logo\/image\/","url":"https:\/\/www.skillovilla.com\/blogs\/wp-content\/uploads\/2021\/07\/logo-thumbnail.png","contentUrl":"https:\/\/www.skillovilla.com\/blogs\/wp-content\/uploads\/2021\/07\/logo-thumbnail.png","width":1200,"height":627,"caption":"SkilloVilla"},"image":{"@id":"https:\/\/www.skillovilla.com\/blogs\/#\/schema\/logo\/image\/"}},{"@type":"Person","@id":"https:\/\/www.skillovilla.com\/blogs\/#\/schema\/person\/f64a2675b6d238b7e44744a87e5c4943","name":"SkilloVilla Team","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/www.skillovilla.com\/blogs\/#\/schema\/person\/image\/","url":"https:\/\/secure.gravatar.com\/avatar\/5e0b6f9e8405f5d6fc302700051e351ffa38fb1cf2709a0cb4e96b5622c497d0?s=96&d=mm&r=g","contentUrl":"https:\/\/secure.gravatar.com\/avatar\/5e0b6f9e8405f5d6fc302700051e351ffa38fb1cf2709a0cb4e96b5622c497d0?s=96&d=mm&r=g","caption":"SkilloVilla Team"},"url":"https:\/\/www.skillovilla.com\/blogs\/author\/sankalp_agarwal"}]}},"_links":{"self":[{"href":"https:\/\/www.skillovilla.com\/blogs\/wp-json\/wp\/v2\/posts\/4003","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.skillovilla.com\/blogs\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.skillovilla.com\/blogs\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.skillovilla.com\/blogs\/wp-json\/wp\/v2\/users\/27"}],"replies":[{"embeddable":true,"href":"https:\/\/www.skillovilla.com\/blogs\/wp-json\/wp\/v2\/comments?post=4003"}],"version-history":[{"count":1,"href":"https:\/\/www.skillovilla.com\/blogs\/wp-json\/wp\/v2\/posts\/4003\/revisions"}],"predecessor-version":[{"id":4004,"href":"https:\/\/www.skillovilla.com\/blogs\/wp-json\/wp\/v2\/posts\/4003\/revisions\/4004"}],"wp:attachment":[{"href":"https:\/\/www.skillovilla.com\/blogs\/wp-json\/wp\/v2\/media?parent=4003"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.skillovilla.com\/blogs\/wp-json\/wp\/v2\/categories?post=4003"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.skillovilla.com\/blogs\/wp-json\/wp\/v2\/tags?post=4003"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}