Deals Of The Week - hours only!Up to 80% off on all courses and bundles.-Close
Introduction
Very simple subqueries
5. Learn about subqueries
Subqueries with multiple results
Correlated subqueries
Other subqueries

Instruction

All right, to give you an idea of what subqueries are, let's analyze the following problem: we want to find cities that have the same rating as Paris.

With the knowledge you have now, you would first need to check the rating for Paris:

SELECT
  Rating
FROM City
WHERE Name = N'Paris';

Then, you would need to write down the result of the above query somewhere in your notebook (the rating is 5, by the way) and then construct a new query:

SELECT
  Name
FROM City
WHERE Rating = 5;

Subqueries have been introduced to help you with such examples. Simply put, they are 'queries within queries', and they are always nested in parentheses. Take a look:

SELECT
  Name
FROM City
WHERE Rating = (
  SELECT
    Rating
  FROM City
  WHERE Name = N'Paris'
);

The database will first check the subquery (in the parentheses), then replace the subquery with its result (in this case, the number 5), and then finally check the outer (main) query.

In this particular example, you must write the subquery in such a way that it returns precisely one value (one column of one row) so that it matches the equation "Rating = X". It wouldn't make much sense to put a whole table there, would it?

Exercise

Show all information about all cities that have the same area as Paris.

Stuck? Here's a hint!

Type:

SELECT
 *
FROM City
WHERE Area = (
  SELECT
    Area
  FROM City
  WHERE Name = N'Paris'
);