Golang Tutorials - Learn Go Programming with Easy Step-by-Step Guides

Explore comprehensive Golang tutorials for beginners and advanced programmers. Learn Go programming with easy-to-follow, step-by-step guides, examples, and practical tips to master Go language quickly.

Nested Query In Sql in SQL

Nested Query In Sql in SQL

? Nested Query (Subquery) in SQL

A Nested Query or Subquery is a query inside another SQL query. The inner query runs first, and its result is used by the outer query.


? Syntax:

SELECT column1, column2FROM table1WHERE column3 IN (    SELECT column3    FROM table2    WHERE condition);

? Example:

Get employees who work in departments located in 'New York':

SELECT employee_nameFROM employeesWHERE department_id IN (    SELECT department_id    FROM departments    WHERE location = 'New York');

? Notes:

  • Subqueries can return:

    • A single value (scalar subquery)

    • A list of values

    • A table/result set

  • Can be used in WHERE, FROM, SELECT, HAVING clauses.

  • Types:

    • Correlated subquery: references outer query columns, runs row-by-row.

    • Non-correlated subquery: runs independently.


Example of Correlated Subquery:

Find employees whose salary is above the average salary of their department:

SELECT employee_name, salary, department_idFROM employees e1WHERE salary > (    SELECT AVG(salary)    FROM employees e2    WHERE e2.department_id = e1.department_id);

Want me to explain specific types of subqueries or write one for your use case?

Disclaimer for AI-Generated Content:
The content provided in these tutorials is generated using artificial intelligence and is intended for educational purposes only.
html
docker
php
kubernetes
golang
mysql
postgresql
mariaDB
sql