Subqueries
You can use a subquery in the SELECT, FROM, WHERE, and JOIN clauses.
-
In WHERE it is better to with IN because you cannot be sure that subquery will return single row. For example:
If you are sure that subquery returns sigle row you can use = instead of IN here -
Subqueries in FROM clause :
Із таблиці tracks группуємо по albumid та обираємо сумму байт кожної групи. Називаємосу сумму байт як SIZE, а всю вибірку іменуємо як album. Далі виконується зовнішній селект середнього значення по стовбчику album.size. -
Correlated subquery. The correlated subquery is a subquery that uses the values from the outer query. Unlike an ordinal subquery, a correlated subquery cannot be executed independently. The correlated subquery is not efficient because it is evaluated for each row processed by the outer query.
For each row processed in the outer query, the correlated subquery calculates the size of the albums from the tracks that belong the current album using the SUM function.SELECT albumid, title FROM albums WHERE 10000000 > ( SELECT sum(bytes) FROM tracks WHERE tracks.AlbumId = albums.AlbumId ) ORDER BY title; -
Subquery in SELECT clause:
(це також корельований підзапит)