#1 India's Top IT Training Institute

On Demand Courses

9 programs

×

About Uncodemy

Know more about who we are and what we stand for.

About Us

About Us

Discover our mission to equip individuals with essential IT skills and industry expertise.

Read More →
UnCodeMy Gallery

UnCodeMy Gallery

Explore highlights from our IT training sessions and success stories.

Read More →
×

Free Resources

Learn, practice and plan your career — bilkul free.

Tutorials

Tutorials

Step-by-step written tutorials to learn any technology at your own pace.

Read More →
Free Counselling

Free Counselling

Book a free video counselling session and pick the right course for you.

Read More →
Online Compiler

Online Compiler

Write, run and test your code online — no setup required.

Read More →

SQL Subqueries Guide
PDF Downloads

Download the SQL subqueries guide PDF from Uncodemy: scalar, IN, NOT IN, correlated and derived-table subqueries, plus join comparisons.

Prepared by: Uncodemy trainer team Reviewed by: Uncodemy Last reviewed: 27 Oct 2026
Types of Subqueries
1
Scalar subqueryReturns one value, e.g. an overall average.
2
IN subqueryReturns a list of values to filter by membership.
3
EXISTS subqueryTrue if any related row is found.
4
Correlated subqueryDepends on the outer row.
5
Derived tableA subquery in FROM: aggregate first, then filter or join.

Quick Answer

This page offers Uncodemy's SQL subqueries guide as a PDF download. A subquery is a query nested inside another. The guide explains scalar subqueries, IN and EXISTS, correlated subqueries and derived tables, shows when a join or a CTE is a better choice and points out the NOT IN trap with nulls.

Download

SQL Subqueries Guide PDF

Download the guide below. Each download is its own file, and everything in it is also explained on this page.

1 PDF Available
PDF 01 Main Guide

SQL Subqueries Guide

Scalar, IN, EXISTS, correlated and derived-table subqueries, the NOT IN trap with NULLs, subquery vs join vs CTE, performance notes and practice tasks, with examples on a customers and orders dataset.

PDF Free Oct 2026
Download PDF

A short form asks for your details before the download starts. Your details are used only to share study material and course information.

01

What is a subquery?

A subquery is a SELECT statement placed inside another statement, usually in brackets. The inner query runs to produce a value, a list of values or a table, and the outer query uses that result. Subqueries let you answer questions in two steps within a single statement, for example: find the orders whose total is above the average order total. The inner query calculates the average, and the outer query compares each order with it.

The examples use these tables: customers(customer_id, name, city, signup_date), orders(order_id, customer_id, order_date, status, order_total), order_items(order_id, product_id, quantity, unit_price) and products(product_id, product_name, category). Dates are text in YYYY-MM-DD form, so the examples run in SQLite and need small changes in other databases.

02

Types of subqueries

Each type returns something different and suits a different kind of question.

TypeReturnsTypical use
Scalar subqueryOne valueCompare each row with an overall average
Multi-row subquery with INA list of valuesFilter by membership
EXISTS subqueryTrue if any row is foundCheck whether related rows exist
Correlated subqueryDepends on the outer rowCompare each row with its own group
Derived table (in FROM)A tableAggregate first, then filter or join
03

A scalar subquery

Orders whose total is above the average of all non-cancelled orders.

SELECT order_id, customer_id, order_total
FROM orders
WHERE status <> 'cancelled'
  AND order_total > (SELECT AVG(order_total)
                     FROM orders
                     WHERE status <> 'cancelled')
ORDER BY order_total DESC;
04

IN and NOT IN

Customers who have placed at least one order, and customers who never have. Note the safer NOT EXISTS form below.

-- customers with at least one order
SELECT customer_id, name
FROM customers
WHERE customer_id IN (SELECT customer_id FROM orders);

-- customers with no orders (NOT EXISTS is null-safe)
SELECT c.customer_id, c.name
FROM customers c
WHERE NOT EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.customer_id);
05

The NOT IN trap with NULL values

NOT IN behaves surprisingly if the subquery returns even one NULL. Because a comparison with NULL is unknown, not true, the whole NOT IN condition becomes unknown for every row and the query can return nothing at all, with no error.

If a column can be NULL, prefer NOT EXISTS, or add a filter such as WHERE column IS NOT NULL inside the subquery. This is a classic interview question and a real source of silent errors in reports.

06

A correlated subquery

Each order is compared with the average of that same customer's orders. The inner query refers to the outer row, so it runs logically once per outer row.

SELECT o.order_id, o.customer_id, o.order_total
FROM orders o
WHERE o.status <> 'cancelled'
  AND o.order_total > (SELECT AVG(o2.order_total)
                       FROM orders o2
                       WHERE o2.customer_id = o.customer_id
                         AND o2.status <> 'cancelled');
07

A derived table in FROM

Aggregate first in a subquery, then join the result to another table.

SELECT c.city, t.orders, t.revenue
FROM (
  SELECT customer_id, COUNT(*) AS orders, SUM(order_total) AS revenue
  FROM orders
  WHERE status <> 'cancelled'
  GROUP BY customer_id
) t
JOIN customers c ON c.customer_id = t.customer_id
ORDER BY t.revenue DESC;
08

Subquery, join or CTE? — and common mistakes

Subquery or join or CTE?

  • Use a join when you need columns from both tables in the result.
  • Use EXISTS or IN when you only need to test for membership or existence.
  • Use a scalar subquery for a single overall value such as an average.
  • Use a CTE when the logic has several steps or is reused.
  • Use a window function when you need group values beside each row without collapsing rows.

Common subquery mistakes

  • A scalar subquery that returns more than one row, which causes an error.
  • NOT IN with NULLs, which returns no rows.
  • Correlated subqueries on huge tables, which can be slow compared with a join.
  • Forgetting aliases for derived tables, which many databases require.
  • Unclear nesting that a CTE would make readable.
09

Practice tasks

Write queries for these questions:

  1. Customers whose total spend is above the average customer spend.
  2. Products never ordered.
  3. The most recent order of each customer using a correlated subquery.
  4. The number of customers per city using a derived table.

Then rewrite each with a join or a CTE and compare which is clearer. Understanding several ways to express the same idea is what makes SQL feel natural.

10

Subquery versus join: which to use

SituationPreferReason
Need columns from both tables in the resultJoinA subquery in WHERE cannot return its columns to the outer query
Only filtering by existenceEXISTS subqueryStops at the first match and reads clearly
Compare with one aggregate valueScalar subqueryShort and readable
Complex multi-step logicCTENamed steps are easier to read and debug
Find rows with no matchNOT EXISTS or LEFT JOIN with IS NULLAvoids the NOT IN problem with NULL values
11

Performance notes

  • Modern optimisers often rewrite subqueries and joins into the same plan, so write the clearer version first.
  • Correlated subqueries run logically once per outer row; check the execution plan if the query is slow.
  • Index the columns used in the correlation and join conditions.
  • Measure on realistic data volumes instead of guessing.

Learn with a trainer

Want to write SQL the way analysts do at work? Explore Uncodemy's Data Analytics course and learn from industry trainers.

View Course
About these PDFs: These PDFs are study material for learning and revision. They are not a certificate, a degree or a promise of a job, and technology changes, so check official documentation for the latest details. Spot an error? Write to info@uncodemy.com and the trainer team will review it.
FAQ

Frequently Asked Questions

What is a subquery in SQL?
A subquery is a query nested inside another query. The inner query produces a value, list or table that the outer query uses.
What is the difference between IN and EXISTS?
IN compares a value with a list returned by a subquery. EXISTS checks whether the subquery returns any row. EXISTS is also safer with NULLs when negated.
What is a correlated subquery?
A subquery that refers to columns from the outer query, so it is evaluated in relation to each outer row.
Why does NOT IN sometimes return no rows?
If the subquery returns a NULL, comparisons become unknown and NOT IN can return nothing. Use NOT EXISTS or filter out NULLs.
When should I use a join instead of a subquery?
Use a join when you need columns from both tables, and a subquery when you only need to filter or test existence.
Are these PDFs free to download?
Yes, the SQL subqueries guide PDF is free. A short form asks for your details before the download starts.