JournalSQLSubqueries and CTEs2 min

For Those Who Do Not Know Subquery

The word Subquery means a query inside a query, or an outer query with an inner query inside it.

  • subquery
  • inner query
  • outer query

The word Subquery means a query inside a query, or an outer query with an inner query inside it.

We can also call a subquery an inner query, and the query outside is called the outer query.

Usually, when writing a subquery, we write the inner query first and test it to make sure it produces the output we want. Afterwards, we write the outer query and run it with confidence that the output will come out right.

Example: Suppose we have an employees table:

photo_2018-02-11_18-58-33

And a departments table:

photo_2018-02-11_18-59-19

If we want to get the employees in the IT department using a subquery, we must break our problem down into smaller problems to solve it. The first thing we think of is getting the id of the IT department, so we write:

SELECT d.id
FROM departments AS d
WHERE d.name = 'IT'

Next, we put this query inside a condition using IN to get all employees who have that same department_id, so we write:

SELECT *
FROM emplyees AS e
WHERE e.department_id IN
  (SELECT d.id
  FROM departments AS d
  WHERE d.name = 'IT')

The output will be:

photo_2018-02-11_18-59-23

I could have used a regular JOIN to link the two tables and filter rows based on the department name IT, but I created this example to illustrate using a subquery. To learn how JOIN works, check out this topic.

Now, what if we want to get all employees in the Data Visualization department? We do the same thing and write:

SELECT *
FROM employees AS e
WHERE e.department_id IN
  (SELECT d.id
  FROM departments AS d
  WHERE d.name = 'Data Visualization')

The output will be:

photo_2018-02-11_18-59-29

What was just explained is called a Simple Subquery, where the inner query executes first, and then we have a set of department IDs that the outer query filters rows by.

Now let's try writing a subquery whose execution depends on the main query (the outer query).

If we want to get the departments that have employees working in them, we write:

SELECT *
FROM departments AS d
WHERE d.id IN
  (SELECT e.department_ID
  FROM employees AS e
  WHERE d.id = e.department_ID)

The output will be:

photo_2018-02-11_18-59-33

If you noticed, the condition in the inner query also depends on the outer query. Therefore, the inner query cannot execute first on its own; instead, both execute together, and this is called a Correlated Subquery.

If you want to learn about the remaining types or ways to use them, you can check out this topic.