What is SubQuery and its advantage/disadvantahes

A subquery in sql sever is a SELECT statement within another SQL statement. The SQL statement can be SELECT, WHERE clause, FROM clause, JOIN, INSERT, UPDATE, DELETE, SET, DO, or another subquery.The query that contains the subquery is normally called outer query and the subquery itself is called inner query.

Why to use subquery:-
(1)Subqueries structure a complex query into isolated parts so that a complex query can be broken down into a series of logical steps for easy understanding and code maintenance. (2)Subqueries allow you to use the results of another query in the outer query.
(3)In some cases, subqueries can replace complex joins and unions and subqueries are easier to understand.

Why not to use subquery:-
(1)When subquery is used, the database server (actually the query optimizer) may need to perform additional steps, such as sorting, before the results from the subquery are used. If a query that contains subqueries can be rewritten as a join, you should use join rather than subqueries. This is because using join typically allows the query optimizer to retrieve data in the most efficient way. In other words, The optimizer is more mature for MySQL for joins than for subqueries, so in many cases a statement that uses a subquery can be executed more efficiently if you rewrite it as a join.

Comments

Popular posts from this blog

Google to FTS Syntax Cheat Sheet

@@rowcount

Sql Index