SQL Subquery interview questions and answers

Q. What is a subquery?
A. Subquery or Inner query or Nested query is a query in a query. A subquery is usually added in the WHERE clause of the sql statement. A subquery can be nested inside a SELECT, INSERT, UPDATE, or DELETE statement or inside another subquery.  Subqueries are an alternate way of returning data from multiple tables.

Q. Can you create a subquery in a From clause?
A. Yes. Subqueries can be used in From, Where and Having clauses. For example, in Sybase

Returns:


Joining virtual tables is one of the most powerful feature of subqueries. Virtual in this context means the result set you are joining is built on the fly. Here is a more advanced example:

Q.What is a correlated subquery?
A. A query is called correlated subquery when both the inner query and the outer query are interdependent. For every row processed by the inner query, the outer query is processed as well. The inner query depends on the outer query before it can be processed.

If a subquery is not dependent on the outer query it is called a non-correlated subquery.

Q. What are the advantages and disadvantages of using a subquery?
A.

Advantages:

  • Subqueries allow you to use the results of another query in the outer query.
  • Subqueries in some complex SQL queries can simplify coding and improve maintainability by breaking down the complex query into a series of logical steps.
  • In some cases, subqueries are easier to understand than complex joins and unions.

Disadvantages:

  •  When a subquery is used, the query optimizer of the database server may have to perform additional steps like sorting the results, etc. Hence, in some cases subqueries can be less efficient than using joins. So, favor joins to subqueries.


300+ Java & Big Data Interview FAQs

16+ Java Key Areas Interview Q&As

800+ Java Interview Q&As

300+ Java & Big Data Tutorials

Top