Google News
logo
SQL - Interview Questions
What is a Subquery? What are its types?
A subquery is a query within another query, also known as nested query or inner query . It is used to restrict or enhance the data to be queried by the main query, thus restricting or enhancing the output of the main query respectively. For example, here we fetch the contact information for students who have enrolled for the maths subject:

SELECT name, email, mob, address
FROM myDb.contacts
WHERE roll_no IN (
	 SELECT roll_no
	 FROM myDb.students
	 WHERE subject = 'Maths');

There are two types of subquery - Correlated and Non-Correlated.
 
* A correlated subquery cannot be considered as an independent query, but it can refer the column in a table listed in the FROM of the main query.

* A non-correlated subquery can be considered as an independent query and the output of subquery is substituted in the main query.
Advertisement