> For the complete documentation index, see [llms.txt](https://gchandra.gitbook.io/data-warehousing/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://gchandra.gitbook.io/data-warehousing/rdbms/sql-concepts/sub-queries.md).

# Sub Queries

A sub-query is a **select query** that is contained inside another query. The inner select query is usually used to determine the results of the outer select query.

**Using Murach Database, find employees who work in Payroll Department.**

```
use Murach;

select 
    department_number
from 
    departments 
where 
    department_name = 'Payroll';

SELECT 
    * 
FROM 
    employees 
where 
    department_number = Value from previous query;
```

### Now using Subquery

```
select 
    * 
from 
    employees 
where 
    department_number = 
    (select 
        department_number 
    from 
        departments 
    where 
        department_name = 'Payroll'

   );
```

**Using Chinook database**, simple Subquery to find out Names of Support Representative

```
SELECT * FROM Employee;

SELECT * FROM Customer;

SELECT * FROM Employee WHERE EmployeeId IN (SELECT SupportRepId FROM Customer);
```

**Using Sakila database**, find the actors who acted in the movie Ace Goldfinger

```
use sakila;

SELECT * FROM actor
WHERE actor_id IN 
    (SELECT actor_id FROM film_actor
    WHERE film_id = 
        (SELECT film_id FROM film 
        WHERE title = 'Ace Goldfinger')
    );
```
