SUBQUERY VS CORELATED QUERY:

It might sound that both of the queries are the same but there is a difference between the two. The difference is the order of how these queries are executed and what the relation between these two queries are. Let's create two sample tables and some sample data. So our initial data setup is like.



Now let's discuss these queries one by one

Normal Sub-query: In this type of query, the outer or parent query and the inner query are independent of each other when executing. In this, the inner query is executed first and then the result set returned by this query is used by the outer query to generate the final result set. Let's write a sub-query with the data setup we created above. This will provide us with all the employees, that has a record in the EmployeeDepartment table. So our query is like the following, with the results.



How the normal sub-query works

First it selects all the records in the EmployeeDepartment table, that returns all the EmployeeId's in the table (4 records). Then, using the IN operator, the outer query gets all the records from the Employees table with an EmployeeId in the result set returned by the inner query, to return only the matching records. So the result is the output that we see above.

Co-related sub-query: In this type of query, the two queries, in other words the outer and the inner query, are dependent or linked to each other, to generate the final result set. Now, let's use the co-related sub-query to get the same results and then we will discuss how they are linked and how it works. Our query changes to the following and we can see the results accordingly.



How co-related sub query works

First of all, the outer query executes and selects the first record from the Employees table. In this case, it is Mark with EmpId as 1. This record is then sent as an input to the inner query, where it checks whether the EmployeeDepartment table has any record with EmployeeId matching the EmpId of the record Mark, received from the outer query. If it finds any match in the EmployeeDepartment table then this record is kept for the result set (since the where condition in the outer query is satisfied by it) else the outer query fetches the next record. Again, the second record is sent as an input to the inner query and this process continues until all the records of the Employees table are traversed by the outer query.

So we can see here that the inner query is dependent on the input or EmpId from the outer query to generate the results. This is how the outer and inner query are linked to each other. So this is how the sub-query and co-related sub-query work.

Comments

Popular posts from this blog