Multi-column subqueries

So far, we have only considered subqueries that return a single column. However, we can also work with subqueries that return multiple columns and multiple rows (derived tables).

Comparison with multiple columns

SQL supports comparison not only with a single column, but also allows pairwise comparison of values in the main query with values in the subquery.

For example, if we want to get information about all reservations where the accommodation price at the time of booking (Reservations.price) matches the current price of the accommodation (Rooms.price), we can do it as follows:

MySQL
SELECT * FROM Reservations
    WHERE (room_id, price) IN (SELECT id, price FROM Rooms);
iduser_idroom_idstart_dateend_datepricetotal
51712019-02-02T12:00:00.000Z2019-02-04T12:00:00.000Z149298
61422020-03-21T09:00:00.000Z2020-03-23T09:00:00.000Z225450
719132020-03-21T10:00:00.000Z2020-04-21T10:00:00.000Z892679
829162019-06-14T10:00:00.000Z2019-06-24T10:00:00.000Z1401400
127192020-05-01T10:00:00.000Z2020-05-02T10:00:00.000Z9999
141372019-09-13T10:00:00.000Z2019-09-17T10:00:00.000Z60240
151252020-05-14T10:00:00.000Z2020-05-15T10:00:00.000Z8080
161052020-03-26T10:00:00.000Z2020-03-27T10:00:00.000Z8080
1711502019-11-18T11:00:00.000Z2019-11-25T11:00:00.000Z80560
1928492020-04-01T11:00:00.000Z2020-04-02T11:00:00.000Z115115
201492020-06-01T10:00:00.000Z2020-06-11T10:00:00.000Z1151150
212482019-11-07T10:00:00.000Z2019-11-10T10:00:00.000Z110330
2212322020-01-14T13:00:00.000Z2020-01-18T13:00:00.000Z52208
2312322019-09-17T13:00:00.000Z2019-09-18T13:00:00.000Z5252
247192020-01-08T13:00:00.000Z2020-01-11T13:00:00.000Z99297
2518192019-11-01T10:00:00.000Z2019-11-16T10:00:00.000Z991485
2621172019-11-03T09:00:00.000Z2019-11-05T09:00:00.000Z215430
2731252020-04-20T09:00:00.000Z2020-04-22T09:00:00.000Z120240
2821142020-02-08T10:00:00.000Z2020-02-12T10:00:00.000Z85340
2921392019-12-08T10:00:00.000Z2019-12-09T10:00:00.000Z150150

In this example, the subquery returns a table with the identifiers of residential properties and their current price:

MySQL
SELECT id, price FROM Rooms
idprice
1149
2225
3150
489
580
6200
760
879
979
10150
11135
1285
1389
1485
15120
16140
17215
18140
1999
20190
21299
22130
2380
24110
25120
2660
2780
28150
2944
30180
3150
3252
3355
3450
3570
3689
3735
3885
39150
4040
4168
42120
43120
44135
45150
46150
47130
48110
49115
5080

And then, using this table, we limit all bookings only to those where the pair of values room_id and price can be found in the subquery table.

The same solution can be applied without the need for comparison across multiple columns, although it would be less concise:

MySQL
SELECT Reservations.* FROM Reservations
INNER JOIN Rooms
ON Reservations.room_id = Rooms.id
WHERE Reservations.price = Rooms.price;