0% found this document useful (0 votes)
2 views2 pages

Nested_Query_SQL_Explanation

Nested queries, or subqueries, are SQL queries that run inside another query, with the inner query executed first to provide results for the outer query. They can be used for filtering or calculations, and can be categorized into single-row and multi-row subqueries. An example demonstrates finding students with marks above the average using a nested query structure.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views2 pages

Nested_Query_SQL_Explanation

Nested queries, or subqueries, are SQL queries that run inside another query, with the inner query executed first to provide results for the outer query. They can be used for filtering or calculations, and can be categorized into single-row and multi-row subqueries. An example demonstrates finding students with marks above the average using a nested query structure.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

Nested Queries in SQL - Detailed Explanation

[Check] What is a Nested Query?

A nested query (or subquery) is a query inside another query. The inner query runs first and its result is used

by the outer query.

[Bullet] Syntax:

SELECT column_name(s)

FROM table_name

WHERE column_name OPERATOR (

SELECT column_name

FROM another_table

WHERE condition

);

[Check] Example: Find Students with Marks Above Average

Table: Students

| ID | Name | Marks |

|----|--------|-------|

| 1 | Aditya | 75 |

| 2 | Rohan | 55 |

| 3 | Sneha | 82 |

| 4 | Priya | 60 |

| 5 | Kavita | 90 |

Query:

SELECT Name, Marks

FROM Students

WHERE Marks > (

SELECT AVG(Marks)

FROM Students

);
Nested Queries in SQL - Detailed Explanation

[Explanation] Explanation:

1. Inner Query:

SELECT AVG(Marks) FROM Students; -> Result = 72.4

2. Outer Query:

SELECT Name, Marks FROM Students WHERE Marks > 72.4;

[Check] Output:

| Name | Marks |

|--------|-------|

| Aditya | 75 |

| Sneha | 82 |

| Kavita | 90 |

[Types] Types of Nested Queries:

1. Single-row subquery (e.g., =, >)

2. Multi-row subquery (e.g., IN, ANY, ALL)

[Multi-row Example] Example (Multi-row):

SELECT Name, Marks

FROM ClassA

WHERE Marks IN (

SELECT Marks

FROM ClassB

);

[Summary] Summary:

- Nested queries are useful for filtering or calculations based on another query.

- They are evaluated from inner to outer.

You might also like