0% found this document useful (0 votes)
0 views3 pages

SQL Subqueries Examples

The document explains subqueries in SQL, which are queries nested within other queries, and provides beginner-friendly examples. It illustrates the use of subqueries in various SQL clauses such as WHERE, SELECT, and FROM, using a sample 'Students' table. Additionally, it includes a correlated subquery example to demonstrate how to compare a student's marks against the average of others.

Uploaded by

Abhi
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)
0 views3 pages

SQL Subqueries Examples

The document explains subqueries in SQL, which are queries nested within other queries, and provides beginner-friendly examples. It illustrates the use of subqueries in various SQL clauses such as WHERE, SELECT, and FROM, using a sample 'Students' table. Additionally, it includes a correlated subquery example to demonstrate how to compare a student's marks against the average of others.

Uploaded by

Abhi
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/ 3

SQL SUBQUERIES - Beginner Friendly Examples

What is a Subquery?

A subquery is a query inside another query.

Used in: SELECT, FROM, WHERE, HAVING

Example Table: Students

| student_id | name | marks |

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

|1 | Riya | 75 |

|2 | Aryan | 82 |

|3 | Diya | 90 |

|4 | Kabir | 60 |

|5 | Meera | 85 |

1. Subquery in WHERE

"Students who scored above average":

SELECT name, marks

FROM Students

WHERE marks > (

SELECT AVG(marks) FROM Students

);
2. Subquery in SELECT

"Each student's marks with class average":

SELECT name, marks,

(SELECT AVG(marks) FROM Students) AS avg_class_marks

FROM Students;

3. Subquery in FROM

"Use a derived table to filter":

SELECT name, marks

FROM (

SELECT * FROM Students

) AS temp

WHERE marks > (

SELECT AVG(marks) FROM Students

);

4. Subquery with IN

"Students who got same marks as those scoring > 80":

SELECT name, marks

FROM Students

WHERE marks IN (
SELECT marks FROM Students WHERE marks > 80

);

Correlated Subquery Example

"Students scoring above average of everyone else":

SELECT name, marks

FROM Students s1

WHERE marks > (

SELECT AVG(marks)

FROM Students s2

WHERE s2.student_id <> s1.student_id

);

Subqueries let you break down complex logic step-by-step!

You might also like