Subqueries – DEV Community

Subqueries – DEV Community


Subqueries are queries that come within another larger query. They are useful to obtain specific information that will later be used in the main query.

Type

Return a single value.

Return multiple rows

It depends on a column in the main query, meaning it is executed once for each row in the outer query.

A subquery that contains another subquery within it.

Returns a single value(similar to single row subquery) but can be used as a column in the SELECT.

A subquery can appear in 3 places of your query:

  • SELECT
  • FROM OR INNER
  • WHERE

And each one of these parts have a set of rules .
For example :

  • A subquery in SELECT should return a single value like:
SELECT 
    e.nombre AS empleado,
    (SELECT d.nombre 
     FROM Departamentos d 
     WHERE d.id = e.departamento_id) AS departamento
FROM Empleados e;
Enter fullscreen mode

Exit fullscreen mode

SELECT NAME FROM EMPLOYEES WHERE DEPARTMENT_ID = (SELECT ID FROM DEPARTMENTS WHERE DEPARTMENT = 'IT');
Enter fullscreen mode

Exit fullscreen mode



Source link

Leave a Reply

Your email address will not be published. Required fields are marked *