SQL / SQL Subqueries and Nested Queries

Using Nested Queries for Advanced Retrieval

In this tutorial, you'll learn how to use nested queries to perform advanced data retrieval tasks. You'll get hands-on experience writing subqueries in SELECT, FROM, and WHERE cla…

Tutorial 2 of 5 5 resources in this section

Section overview

5 resources

Explores how to use subqueries and nested queries for advanced data retrieval.

1. Introduction

In this tutorial, we'll dive into the powerful technique of using nested queries for advanced data retrieval, often referred to as subqueries. Subqueries are SQL queries that are nested inside other SQL queries and can return data that will be used in the main query.

What you will learn:
- Understanding of nested queries and their applications
- How to write subqueries in SELECT, FROM, and WHERE clauses
- Best practices for writing and optimizing nested queries

Prerequisites:
- Basic understanding of SQL
- Familiarity with SELECT, FROM, and WHERE clauses

2. Step-by-Step Guide

A subquery can be used in the SELECT, FROM, and WHERE clauses, and it's executed once before the main query. The result of the subquery is then passed on to the main query for its execution.

Using Subquery in SELECT clause:
The subquery in the SELECT clause is used when you want to perform operations on a single column and return the output in the main select query.

Using Subquery in FROM clause:
The subquery in the FROM clause is used when you want to perform operations on multiple columns and return the result in the main select query.

Using Subquery in WHERE clause:
The subquery in the WHERE clause is used when you want to filter the results of the main query based on the results of the subquery.

3. Code Examples

Example 1: Subquery in SELECT clause

SELECT employee_name, 
       (SELECT count(*) 
        FROM employee_table 
        WHERE department_id = 1) AS count_of_department_1
FROM employee_table;

In this example, the subquery counts the number of employees in department 1 and returns this value for each row of the main query.

Expected Result:
A table with the name of each employee and the count of employees in department 1.

Example 2: Subquery in FROM clause

SELECT employee_name, AVG(salary) 
FROM 
   (SELECT employee_name, salary 
    FROM employee_table 
    WHERE department_id = 1) AS subquery_table
GROUP BY employee_name;

In this example, the subquery returns the name and salary of employees in department 1. The main query then calculates the average salary of these employees.

Expected Result:
A table with the name of each employee in department 1 and their average salary.

Example 3: Subquery in WHERE clause

SELECT employee_name, salary 
FROM employee_table 
WHERE salary > 
   (SELECT AVG(salary) 
    FROM employee_table);

In this example, the subquery calculates the average salary of all employees. The main query then returns the names and salaries of employees who earn more than this average.

Expected Result:
A table with the name and salary of each employee who earns above the average salary.

4. Summary

In this tutorial, we have learned how to use subqueries in SELECT, FROM, and WHERE clauses to perform advanced data retrieval tasks.

Next steps:
- Practice writing subqueries with different datasets
- Learn about correlated subqueries and how they differ from the subqueries we've discussed in this tutorial

Additional resources:
- SQL Subqueries - W3Schools
- Subqueries in SQL - GeeksforGeeks

5. Practice Exercises

Exercise 1:
Write a query that returns the name and department of employees who earn more than the average salary in their department.

Solution:

SELECT employee_name, department_id 
FROM employee_table 
WHERE salary > 
   (SELECT AVG(salary) 
    FROM employee_table 
    GROUP BY department_id);

This query first calculates the average salary for each department. It then returns the name and department of employees who earn more than this average.

Exercise 2:
Write a query that returns the name of the department with the highest average salary.

Solution:

SELECT department_name 
FROM department_table 
WHERE department_id = 
   (SELECT department_id 
    FROM employee_table 
    GROUP BY department_id 
    ORDER BY AVG(salary) DESC 
    LIMIT 1);

This query first calculates the average salary for each department and returns the ID of the department with the highest average salary. It then returns the name of this department.

Tips for further practice:
- Try writing subqueries in the HAVING clause
- Write a subquery that returns a list of employees who earn more than their manager.

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

AES Encryption/Decryption

Encrypt and decrypt text using AES encryption.

Use tool

QR Code Generator

Generate QR codes for URLs, text, or contact info.

Use tool

Fake User Profile Generator

Generate fake user profiles with names, emails, and more.

Use tool

Random Name Generator

Generate realistic names with customizable options.

Use tool

Interest/EMI Calculator

Calculate interest and EMI for loans and investments.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help