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

Q.What is a correlatedsubquery?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.