Now we will execute the main query (Outer query), as Subquery is being used as an expression in Where clause of Outer Query. Once you execute the Subquery, it returns all SalesIds which belongs to Year 2020. Lets understand the above query by breaking it in parts, first we will check the output of subquery (inner query). You can also use subquery as an expression in Where Clause, Lets modify the above query and make it return the same result using subquery as an expression in WHERE clause. You can see, it returns Product Wise sales done by individual sales person, also this sales will be for year 2020 as Outer query uses the output returned by Subquery that is sales done for year 2020. Now we will execute main query(Outer Query) that is completer query. Lets understand the statement by breaking it into two parts, firstly we will execute the subquery (inner query) and see the output return by subquery, and secondly we will execute the complete query to see the output.Īs you can see, it returns all the details of sales which are done in Year 2020. GROUP BY subqry.SalesPerson, subqry.Product SELECT subqry.SalesPerson,įROM dbo.SalesDetails WHERE YEAR(DATE)=2020 Subquery (inner query) fetches all the sales which are done in year 2020, then main Query (Outer query) uses output returned by subquery and returns Product wise Sales done by individual Sales in year 2020. In following statement you can see, two select statement, a subquery that is inner query and main query (outer query). Lets see the example of using subquery in select statement, Now we have a table named as SalesDetails as shown below. Lets look at an example of Subquery in SQL Server.įirst we prepare a table first then insert some records into table using below scripts. Subqueries must enclose within the parenthesis.Where, Group by, Having clause can be used in a subquery.Order by Clause cannot be used in a subquery. A subquery is usually added within the Where Clause of another SQL select statement.A Subquery can be used with a Select, Insert, Update, or Deletestatement along with comparison or logical operator such as > = ,There are some guidelines to consider when using subqueries as given below. The outer query is called as main query and inner query is called as subquery.Ī subquery (inner query) executes first then main query (outer query) executes and main query (outer query) use the subquery result. A Subquery is a query within another query.
0 Comments
Leave a Reply. |