Sub Queries in SQL with Best 1 Example

  • Sub Queries are simply a select statement, that returns a single value and can be nested inside a select, update or delete statement. It is also possible to nest a sub query inside another sub query.
  • Sub Query can be nested up to 32 levels
  • Sub Query are always enclosed in parentheses or round bracket and are called as inner queries. The query containing the sub query is called as outer query.
  • The columns from a table i.e. present only inside a sub query, can not be used in the select list of the outer query.

Syntax

Select * from
Where condition operator ( select column_name from inner_table_name)

Better to read the previous topic to get good understanding on the above points.
Stored Procedure in SQL
Function in SQL
Stored Procedure vs Function

Correlated Sub Queries

If the sub query depends on the outer query for it’s values, then that sub query is called as Correlated Sub Queries.
Sub query can not be executed independently.

Example:-

Select name, (select sum(quantity_sold) from productsales where id = product.id) as TotalQuantitySold
From product 
Order by name

For more details refer Microsoft Link

Leave a Comment

Your email address will not be published. Required fields are marked *