SQL Subquery vs JOIN: Simple Explanation with Easy Examples

A subquery is a query (SQL statement) inside another query.It’s like asking one question inside another question to get your final answer.

Syntax:

sql

SELECT column_name
FROM table_name
WHERE column_name = (SELECT column_name FROM another_table WHERE condition);
  • The inner query runs first and returns a result.
  • The outer query then uses that result.

Example of a Subquery

Imagine two tables:

students

idnameclass_id
1Ramesh101
2Priya102
3Amit101

classes

class_idclass_name
101Science
102Arts

Question: Find students who belong to Science class.

Using subquery:

sql

SELECT name
FROM students
WHERE class_id = (SELECT class_id FROM classes WHERE class_name = 'Science');

Steps:

  1. Inner query: (SELECT class_id FROM classes WHERE class_name = 'Science') → gives 101
  2. Outer query: SELECT name FROM students WHERE class_id = 101 → gives Ramesh, Amit

What is a JOIN?

A JOIN combines rows from two or more tables based on a related column.
Instead of asking one question inside another, you merge data together.

Example with JOIN:

sql

SELECT students.name, classes.class_name
FROM students
JOIN classes ON students.class_id = classes.class_id
WHERE classes.class_name = 'Science';

Result:

nameclass_name
RameshScience
AmitScience

Difference Between Subquery and JOIN

FeatureSubquery (Nested Query)JOIN (Table Combination)
DefinitionQuery inside another queryCombines rows from two or more tables
ExecutionInner query runs first, then outer query uses resultBoth tables are scanned and matched at same time
PerformanceSometimes slower (depends on DB & indexes)Often faster for related data
ReadabilityEasy for simple checksBetter for comparing columns across tables
Use caseWhen you need a value from another query (single/multi)When you need columns from multiple tables

Think of it like real life:

  • Subquery = “I’ll first ask the librarian which room Science class is in (inner query), then I’ll ask which students are in that room (outer query).”
  • JOIN = “I’ll take the list of students and the list of classes, and directly match them together in one go.”