Subquery

A subquery (also known as a nested query) is an SQL query that is embedded inside another SQL query.

Explanation:

  • Subqueries are used to fetch data dynamically from one table and use it in another query.
  • They can be used with SELECT, INSERT, UPDATE, or DELETE statements.
  • They can be correlated (dependent on the outer query) or non-correlated (independent).

Example:

Find employees who earn more than the average salary in the company.

sqlCopyEditSELECT name, salary FROM Employees
WHERE salary > (SELECT AVG(salary) FROM Employees);

Here, the subquery (SELECT AVG(salary) FROM Employees) calculates the average salary, and the outer query fetches employees earning more than this value.