When a query contains a subquery, the database first runs the subquery to get its result. This result is then used by the outer query to filter or select rows. For example, to find employees in the 'Sales' department, the subquery finds the department id for 'Sales'. The outer query then selects employees with that department id. The outer query waits for the subquery to finish because it needs the subquery's value to continue. If the subquery returns multiple values but the outer query expects one, an error occurs. This nesting of queries allows building complex queries step-by-step.