Eda Eren

August 16, 2023
  • SQL

A simple example of a nested SQL query

Let's say we have this table:

citycountrypopulationlatitudelongitude
GuadalajaraMexico150080020.659699-103.349609
TorontoCanada279506043.653226-79.383184
HoustonUnited States219591429.760427-95.369803
New YorkUnited States840583740.712784-74.005941
PhiladelphiaUnited States155316539.952584-75.165222
HavanaCuba210614623.05407-82.345189
Mexico CityMexico855550019.432608-99.133208
PhoenixUnited States151336733.448377-112.074037
Los AngelesUnited States388430734.052234-118.243685
Ecatepec de MorelosMexico174200019.601841-99.050674
MontrealCanada171776745.501689-73.567256
ChicagoUnited States271878241.878114-87.629798

We want to get all the cities west of Chicago. As we go towards the west, the longitude must be less than the longitude of Chicago — the west of the prime meridian has longitudes that are negative numbers.

Here is the pseudocode:

SELECT * FROM north_american_cities
WHERE longitude < ${Chicago's longitude}
SELECT * FROM north_american_cities
WHERE longitude < ${Chicago's longitude}

So, what we need to do is somehow get the value of Chicago's longitude and use it as comparison. It is by itself easy:

SELECT longitude FROM north_american_cities
WHERE city = 'Chicago';
SELECT longitude FROM north_american_cities
WHERE city = 'Chicago';

What we can do is simply put it inside the parenthesis and use it as a value itself, just like a variable:

SELECT * FROM north_american_cities
WHERE longitude < (
SELECT longitude
FROM north_american_cities
WHERE city = 'Chicago'
);
SELECT * FROM north_american_cities
WHERE longitude < (
SELECT longitude
FROM north_american_cities
WHERE city = 'Chicago'
);

The result is this:

citycountrypopulationlatitudelongitude
GuadalajaraMexico150080020.659699-103.349609
HoustonUnited States219591429.760427-95.369803
Mexico CityMexico855550019.432608-99.133208
PhoenixUnited States151336733.448377-112.074037
Los AngelesUnited States388430734.052234-118.243685
Ecatepec de MorelosMexico174200019.601841-99.050674

Furthermore, we can order the longitudes from west to east using the ORDER BY clause:

SELECT * FROM north_american_cities
WHERE longitude < (
SELECT longitude
FROM north_american_cities
WHERE city = 'Chicago'
)
ORDER BY longitude;
SELECT * FROM north_american_cities
WHERE longitude < (
SELECT longitude
FROM north_american_cities
WHERE city = 'Chicago'
)
ORDER BY longitude;

And, voilà:

citycountrypopulationlatitudelongitude
Los AngelesUnited States388430734.052234-118.243685
PhoenixUnited States151336733.448377-112.074037
GuadalajaraMexico150080020.659699-103.349609
Mexico CityMexico855550019.432608-99.133208
Ecatepec de MorelosMexico174200019.601841-99.050674
HoustonUnited States219591429.760427-95.369803

The example is taken from sqlbolt.com.