Hackforge Academy

Category: sql

what is sub query in sql

Published on 24 May 2026

Explanation

A subquery is a query written inside another SQL query. It is used to fetch intermediate data that is used by the main query.

Code:

SELECT * FROM employees WHERE 
salary > (SELECT AVG(salary) 
FROM employees);

Explanation

Subqueries can be used inside WHERE clauses to filter records based on another query result.

Code:

SELECT name FROM students WHERE 
marks > (SELECT AVG(marks) 
FROM students);

Explanation

A subquery can return a single value, multiple values, or even an entire table depending on usage.

Code:

SELECT * FROM products WHERE 
category_id IN 
(SELECT id FROM categories WHERE 
status = 'active');

Explanation

Subqueries are commonly used for comparisons, filtering, existence checks, and nested calculations.

Code:

SELECT * FROM orders WHERE 
EXISTS (SELECT 1 FROM customers 
WHERE customers.id =
 orders.customer_id);

Explanation

A correlated subquery depends on the outer query and executes once for each row of the outer query.

Code:

SELECT e1.name FROM employees e1 WHERE 
salary > (SELECT AVG(salary)
 FROM employees e2 
WHERE e1.department_id = e2.department_id);

πŸš€ Learn Spring Boot with real-world projects

πŸ’‘ Build REST APIs step by step

🧠 Improve backend development skills

🎯 Get career-ready practical training

Join Our Free WhatsApp Community

Direct access to niche-specific mentors and peers on WhatsApp.

🐍

Python Community

Discuss Django, FastAPI, AI integration, and automation scripts with 15k+ developers.

Join Python Community
βš›οΈ

React Community

Master Next.js, Framer Motion, and State Management. Share your latest UI components.

Join React Community
β˜•

Java Community

Deep dives into Spring Boot, Microservices architecture, and high-performance backend ops.

Join Java Community