Knowledge Guide
HomeDatabasesSQL Fundamentals

Nested Query

Nested queries, also known as subqueries, are SQL queries that are embedded within another SQL query. They can be used in various parts of the main query, including the SELECT, FROM, WHERE, and HAVING clauses.

Subqueries enable complex operations and can be crucial for performing advanced data manipulations and analyses directly within the database.

Example

Consider we have students and exam_results table with the following data, and we want to fetch the names of students who scored above 92 in at least 1 subject.

Image
Image
Image
Image

Query

SELECT student_name FROM Students WHERE student_id IN ( SELECT student_id FROM Exam_Results WHERE score > 92 );
java
SELECT student_name
FROM Students
WHERE student_id IN (
    SELECT student_id
    FROM Exam_Results
    WHERE score > 92
);

Result

Executing the above query will fetch the names of students who scored more than 92 marks in any subject.

Image
Image

Usage of Nested Queries

🤖 Don't fully get this? Learn it with Claude

Stuck on Nested Query? Open Claude, copy a block below, and it'll teach you this exact concept — visually and interactively.

🎨 Explain it visually

Build the mental picture, not memorization.

I just read a lesson on **Nested Query** (Databases) and want to truly understand it. Explain Nested Query from first principles using ONE vivid real-world analogy and a visual mental model — draw it as ASCII art or a clear step-by-step diagram — with a concrete example using real numbers. Then ask me one question to check I got the mental picture, and wait for my reply. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
🤔 Walk me through it (interactive)

Socratic — adapts to where you're stuck.

Teach me **Nested Query** interactively. Ask me ONE guiding question at a time, wait for my answer, and adapt to my confusion — build the idea with me step by step instead of explaining it all at once. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
🧪 Quiz me & fix my gaps

Active recall exposes what you missed.

Quiz me on **Nested Query** with 5 questions, easy to tricky, ONE at a time. Tell me if each answer is right; at the end, explain clearly what I got wrong and why. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
🧠 Make it stick

Intuition + hook + flashcards for long-term memory.

Help me remember **Nested Query** for the long term: give the one-sentence intuition, a memorable hook/mnemonic, a tiny worked example, and 3 active-recall flashcards (Q -> A). If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.

📝 My notes