Mastering SQL: From Fundamentals to Advanced Techniques
Nested Queries in SQL - Query In Query
Overview
S.Q.L. (Structured Query Language) is a language used to operate R.D.B.M.s (Relational Database Management System). A handy feature in SQL is nesting a query within another. The nested query is also referred to as a subquery.
This article aims at shedding some light on nested queries with the SELECT, DELETE, and INSERT statements, the usage of subqueries within WHILE clauses, etc. All code blocks in this article shall adhere to MySQL standards.
Scope
In this article we shall learn about:
- What is a nested query?
- How to create a nested query?
- Some fine examples.
This article doesn’t concern itself with:
- Any other unrelated SQL or DBMS concepts.
What is a nested query?
As the name suggests, a query nested within another query (as a part of it) is referred to as a nested query. There can be several levels of nesting, such that a query has a query nested in it, and the nested query (subquery) has itself in turn another query nested in it, and so on.
Let us say there is a query mainQuery having another query subQuery nested within it. subQuery is evaluated first, and then its results are made available to the mainQuery.
How to create a nested query?
Following are some common syntax patterns for creating a subquery:
Sub-queries can be used in aggregation, function calls, etc as well.
Examples
Let us create a dummy database and a table in it to be able to understand code demonstrations better.
Output
Output
- The following code block prints the names of all the employed characters:
The following code snippet dictates how to use a subquery in a WHERE clause:
Output
- The following code block depicts how one may delete an entry from a table based on the result of a sub-query:
Output
Conclusion
- A handy feature in SQL is nesting a query within another. The nested query is also referred to as a subquery.
- There can be several levels of nesting, such that a query has a query nested in it, and the nested query (subquery) has itself in turn another query nested in it, and so on.