SQL Subqueries Explained: Types, Examples, and Best Practices

🚀 SQL Journey – Days 27–29: Subqueries Over the past 3 days, I dived deep into one of the most powerful SQL concepts — Subqueries. What started as a basic concept evolved into a problem-solving mindset for handling complex queries efficiently. 🔹 What is a Subquery? A Subquery is a query written inside another SQL query. 👉 It helps break complex problems into smaller logical steps 👉 Executes first and provides results to the outer query SELECT column_name FROM table_name WHERE column_name = (SELECT column_name FROM table_name); 🔹 Where Subqueries Can Be Used? ✔ Inside SELECT ✔ Inside WHERE ✔ Inside FROM (Derived tables) 🔹 Types of Subqueries (Deep Understanding) ✅ 1. Single Row Subquery • Returns only one value • Used with: =, >, <, >=, <= 📌 Example: SELECT name FROM employees WHERE salary > (SELECT AVG(salary) FROM employees); ✅ 2. Multi Row Subquery • Returns multiple values • Used with: IN, ANY, ALL 📌 Example: SELECT name FROM employees WHERE department_id IN (SELECT department_id FROM departments); ✅ 3. Correlated Subquery • Depends on the outer query • Executes row by row 📌 Example: SELECT e1.name FROM employees e1 WHERE salary > ( SELECT AVG(salary) FROM employees e2 WHERE e1.department_id = e2.department_id ); ⚠️ Powerful but can impact performance if not optimized 🔹 Subqueries Based on Location (Real-World Scenario) Location-based queries are very common in real applications like HR systems, delivery apps, etc. 📍 Example 1: Employees earning above average in a specific location SELECT name FROM employees WHERE salary > ( SELECT AVG(salary) FROM employees WHERE location = 'Hyderabad' ); 📍 Example 2: Employees working in locations with high salary departments SELECT name FROM employees WHERE location IN ( SELECT location FROM employees WHERE salary > 50000 ); 📍 Example 3: Correlated subquery based on location SELECT e1.name FROM employees e1 WHERE salary > ( SELECT AVG(salary) FROM employees e2 WHERE e1.location = e2.location ); 👉 This compares each employee with the average salary of their own location 🔹 Key Concepts Learned ✔ Subqueries execute inside → outside ✔ Outer query depends on inner query results ✔ Data types must match ✔ Can be nested multiple levels ✔ Used for dynamic and flexible conditions 💡 Rule of thumb: 👉 Use subqueries for clarity 👉 Use JOINs for performance (when needed) 🔹 Interview Focus 💡 • Difference between correlated & non-correlated subqueries • When to use IN vs EXISTS • Subquery vs JOIN (performance questions) • Execution order of queries 🔹 Real Practice Scenarios ✔ Employees earning above average ✔ Department-wise comparisons ✔ Location-based filtering ✔ Dynamic conditions using nested queries ✔ Replacing joins with subqueries (and vice versa) #SQL #Subqueries #AdvancedSQL #DataAnalytics #LearningJourney #RDBMS #TechJourney #CSE

  • No alternative text description for this image

To view or add a comment, sign in

Explore content categories