• Latest
  • Trending
Understanding Subqueries in SQL

Understanding Subqueries in SQL

February 9, 2022
Absa and Visa Extend Strategic Partnership to Advance Growth and Innovation Across Africa

Absa and Visa Extend Strategic Partnership to Advance Growth and Innovation Across Africa

July 29, 2025
French Telco Orange Hit by Cyber-Attack

French Telco Orange Hit by Cyber-Attack

July 29, 2025
ATC Ghana supports Girls-In-ICT Program

ATC Ghana supports Girls-In-ICT Program

April 25, 2023
Vice President Dr. Bawumia inaugurates  ICT Hub

Vice President Dr. Bawumia inaugurates ICT Hub

April 2, 2023
Co-Creation Hub’s edtech accelerator puts $15M towards African startups

Co-Creation Hub’s edtech accelerator puts $15M towards African startups

February 20, 2023
Data Leak Hits Thousands of NHS Workers

Data Leak Hits Thousands of NHS Workers

February 20, 2023
EU Cybersecurity Agency Warns Against Chinese APTs

EU Cybersecurity Agency Warns Against Chinese APTs

February 20, 2023
How Your Storage System Will Still Be Viable in 5 Years’ Time?

How Your Storage System Will Still Be Viable in 5 Years’ Time?

February 20, 2023
The Broken Promises From Cybersecurity Vendors

Cloud Infrastructure Used By WIP26 For Espionage Attacks on Telcos

February 20, 2023
Instagram and Facebook to get paid-for verification

Instagram and Facebook to get paid-for verification

February 20, 2023
YouTube CEO Susan Wojcicki steps down after nine years

YouTube CEO Susan Wojcicki steps down after nine years

February 20, 2023
Inaugural AfCFTA Conference on Women and Youth in Trade

Inaugural AfCFTA Conference on Women and Youth in Trade

September 6, 2022
  • Consumer Watch
  • Kids Page
  • Directory
  • Events
  • Reviews
Friday, 17 July, 2026
  • Login
itechnewsonline.com
  • Home
  • Tech
  • Africa Tech
  • InfoSEC
  • Data Science
  • Data Storage
  • Business
  • Opinion
Subscription
Advertise
No Result
View All Result
itechnewsonline.com
No Result
View All Result

Understanding Subqueries in SQL

by ITECHNEWS
February 9, 2022
in Data Science, Leading Stories
0 0
0
Understanding Subqueries in SQL

Overview

  • Be familiar with the SELECT Statement

  • Have a basic understanding of WHERE HAVING and FROM clauses

    YOU MAY ALSO LIKE

    French Telco Orange Hit by Cyber-Attack

    ATC Ghana supports Girls-In-ICT Program

Introduction

In this article, we will deal with Subqueries in SQL. Like any structure has a subpart or a subset similarly our Query in SQL or the SELECT query in SQL also has a concept of Subquery associated with it.

We will be learning about subqueries from the scratch covering all your questions like What a Subquery Is? What are the different types of Subqueries? Why are they even required? Where can sub queries be used or with which clauses/statements we can use them etc. etc.

Don’t worry! Everything will be explained with the help of easy-to-understand examples.

We will be using MS SQL Server as our Database Server!

Table of Contents

  • Understanding the Dataset

  • What is a Subquery?

  • What is a Subquery used for?

  • Types of Subqueries in SQL

  • Ordinary Subquery

1. Subqueries with SELECT Statement

2. Subqueries with WHERE Clause

3. Subqueries with HAVING Clause

  • Inline View

  • Correlated Subquery

Understanding the Dataset

This dataset will be used for all the examples that we will be taking in this article.

We have a table named ORDERS that contains the records of the sales made in a particular period of time for various products under multiple categories.

It contains columns like: Order_Id, Category , Product, Sales

Subqueries in SQL

Let’s begin our learning with a situation!

We have the Table: ORDERS as –

Subqueries in SQL

Suppose that I want to see only those entries where the sales made is more than the average sales of all the entries received till now.

So my question to you is: Can you show the records where the sales are more than the overall average sales.

We can try something like :

SELECT * FROM ORDERS
WHERE Sales > AVG(Sales)

But we get an ERROR!

“An aggregate may not appear in the WHERE clause unless it is in a subquery contained in an outer reference”

Hold on a second, What does the word subquery mean here?

It is a query within a query

We can perform this task easily using something known as a ‘SUBQUERY’

How?

We will write the query as:

SELECT * FROM ORDERS
WHERE Sales > (SELECT AVG(Sales) FROM ORDERS)

SELECT AVG(Sales) FROM ORDERS is our Subquery here(also known as the inner query)

SELECT AVG(Sales) FROM ORDERS

It outputs :

This output is then used as an input for our main query(also known as the outer query)

SELECT * FROM ORDERS
WHERE Sales > (SELECT AVG(Sales) FROM ORDERS)

We get the final output as :

Subqueries in SQL

Let’s officially define what a Subquery is :

What is a Subquery?

A Subquery is a query within another SQL query.

Note that it must always be enclosed within parentheses.

When is a Subquery used?

When we want to do some operations or perform some calculations at a different level as we did in the inner query explained above (We calculated the overall average sales)

and other operations at a different level like we did in the outer query explained above (We compared the individual sales with the overall sales for each record).

In a nutshell, When we want to perform operations at different levels then we use a Subquery.

Types of Subqueries in SQL

There are 3 types of Subqueries in SQL. They are :

  1. Ordinary Subquery

  2. Inline View

  3. Correlated Subquery

Let’s learn each of them one by one :

Ordinary Subquery

The query that we learned at the beginning is a perfect example of an Ordinary Subquery.

Let’s take some more examples :

We have the Table: ORDERS as –

Ordinary Summary | Subqueries in SQL

Subqueries with SELECT Statement

Question: Show the category-wise percentage of Sales done.

We will write the query as :

SELECT Category , SUM(Sales)/(SELECT SUM(Sales) FROM ORDERS) AS PERC_SALES
FROM ORDERS
GROUP BY Category

How does the query work?

First, the inner query gets executed.

SELECT SUM(Sales) FROM ORDERS

Then using this value the outer query executes.

FINAL OUTPUT :

Subqueries with WHERE Clause

Question: Show the records where the sales are more than the overall average sales.

We will write the query as:

SELECT * FROM ORDERS
WHERE Sales > (SELECT AVG(Sales) FROM ORDERS)

 How does the query work?

First, the inner query gets executed.

SELECT AVG(Sales) FROM ORDERS

It outputs :

Then using this value the outer query executes.

FINAL OUTPUT :

Subqueries with HAVING Clause

Question: Show the items where average sales for each item is more than the overall average.

We will write the query as:

SELECT Product , AVG(Sales)
FROM ORDERS
GROUP BY Product
HAVING AVG(Sales) > (SELECT AVG(Sales) FROM ORDERS)

How does the query work?

By the time you must be knowing that: First the inner query gets executed.

SELECT AVG(Sales) FROM ORDERS

It outputs :

Then using this value the outer query executes.

FINAL OUTPUT :

Important features of ORDINARY SUBQUERIES :

  1. Used with SELECT Statement, WHERE Clause, HAVING Clause, CASE WHEN Statement

  2. Here first the subquery(inner query) is executed and then the main query(outer query) gets executed taking the output of the subquery.

  3. The inner query works independently and can query a different table as well.

  4. It must return only one column in the output (at the maximum).

Inline View

Let’s take a simple example :

To get all the records in the table we can do,

SELECT * FROM ORDERS

We can replace the table(ORDERS) here with a subquery as well (SELECT * FROM ORDERS)

This is known as an inline view.

SELECT * FROM
( SELECT * FROM ORDERS) TT

OUTPUT :

Inline view

Let’s move on to a more complex question.

Question: Display the record with the 2nd lowest sales.

We will write the query as:

SELECT *
FROM (SELECT *, ROW_NUMBER() OVER (ORDER BY Sales) AS row_num FROM ORDERS) AS T
WHERE row_num=2

How does the query work?

By the time you must be knowing that: First, the inner query gets executed.

SELECT *, ROW_NUMBER() OVER(ORDER BY Sales) AS row_num FROM ORDERS

It outputs :

Subqueries in SQL

Then using this value the outer query executes. The OUTPUT table above is used as a table to retrieve the second lowest sales record.

FINAL OUTPUT :

Important features of INLINE VIEW :

  1. Used with FROM Clause i.e when we write a query in the FROM Clause.

  1. It is a subquery in the FROM Clause of a SELECT Statement

  2. This is used when we have written some query (known as the inner query) and we want to use the output of that inner query as a table for the outer query.

  3. Remember that, It is mandatory to write the table alias at the end of the FROM Clause.

  4. It looks like nesting SELECT Statements.

But why do we actually need to put a SELECT Statement in the FROM Clause?

Here we are creating a column named row_num in the inner query and we want to filter it which is done with the help of the outer query.

Correlated Subquery

Let us learn this with the help of an example :

Question: Display all the products whose sales are more than the average sales in their category.

We will write the query as:

SELECT Order_Id , Product, Category
FROM ORDERS ord
WHERE Sales >= (SELECT AVG(Sales) FROM ORDERS WHERE Category = ord.Category)

How does the query work?

The subquery is executed once for every row of the outer query.

Correlated Subquery | Subqueries in SQL

FINAL OUTPUT :

Important features of CORRELATED SUBQUERIES:

  1. Used for the row-by-row processing

  2. Used when we want the subquery to return a varied result(s) for each row considered by the main query(Outer query)

  3. Operators like ANY and ALL can be used in a correlated query.

A Subquery can be used with the SELECT, INSERT, UPDATE, and DELETE statements.

Conclusion

So this is how Subqueries work and help us achieve results when we want them at different levels of calculations.

Source: Abhishek Jain
Via: analyticsvidhya
Tags: Subqueries in SQL
ShareTweet

Get real time update about this post categories directly on your device, subscribe now.

Unsubscribe

Search

No Result
View All Result

Recent News

Absa and Visa Extend Strategic Partnership to Advance Growth and Innovation Across Africa

Absa and Visa Extend Strategic Partnership to Advance Growth and Innovation Across Africa

July 29, 2025
French Telco Orange Hit by Cyber-Attack

French Telco Orange Hit by Cyber-Attack

July 29, 2025
ATC Ghana supports Girls-In-ICT Program

ATC Ghana supports Girls-In-ICT Program

April 25, 2023

About What We Do

itechnewsonline.com

We bring you the best Premium Tech News.

Recent News With Image

Absa and Visa Extend Strategic Partnership to Advance Growth and Innovation Across Africa

Absa and Visa Extend Strategic Partnership to Advance Growth and Innovation Across Africa

July 29, 2025
French Telco Orange Hit by Cyber-Attack

French Telco Orange Hit by Cyber-Attack

July 29, 2025

Recent News

  • Absa and Visa Extend Strategic Partnership to Advance Growth and Innovation Across Africa July 29, 2025
  • French Telco Orange Hit by Cyber-Attack July 29, 2025
  • ATC Ghana supports Girls-In-ICT Program April 25, 2023
  • Vice President Dr. Bawumia inaugurates ICT Hub April 2, 2023
  • Home
  • InfoSec
  • Opinion
  • Africa Tech
  • Data Storage

© Copyright 2026, All Rights Reserved | iTechNewsOnline.Com - Powered by BackUPDataSystems

Welcome Back!

Login to your account below

Forgotten Password?

Retrieve your password

Please enter your username or email address to reset your password.

Log In

Add New Playlist

No Result
View All Result
  • Home
  • Tech
  • Africa Tech
  • InfoSEC
  • Data Science
  • Data Storage
  • Business
  • Opinion

© Copyright 2026, All Rights Reserved | iTechNewsOnline.Com - Powered by BackUPDataSystems

Are you sure want to unlock this post?
Unlock left : 0
Are you sure want to cancel subscription?
Go to mobile version