Subqueries

You can use a subquery in the SELECT, FROM, WHERE, and JOIN clauses. 

  1. In WHERE it is better to with IN because you cannot be sure that subquery will return single row. For example: 

    SELECT customerid, 
    firstname,  
    lastname  
    FROM customers  
    WHERE supportrepid IN  
    ( SELECT employeeid FROM employees WHERE country = 'Canada' ); 
    
    If you are sure that subquery returns sigle row you can use = instead of IN here 

  2. Subqueries in FROM clause : 

    SELECT AVG(album.size)  
    FROM  
    ( SELECT 
     SUM(bytes) AS SIZE 
     FROM tracks 
     GROUP BY albumid ) AS album; 
    
    Із таблиці tracks  группуємо по albumid та обираємо сумму байт кожної групи. Називаємосу сумму байт як SIZE, а всю вибірку іменуємо як album. Далі виконується зовнішній селект середнього значення по стовбчику album.size.  

  3. 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. 

    SELECT albumid, title 
     FROM albums 
     WHERE 10000000 > ( SELECT 
         sum(bytes) 
         FROM tracks 
         WHERE tracks.AlbumId = albums.AlbumId ) 
     ORDER BY title;
    
    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. 

  4. Subquery in SELECT clause: 

    SELECT albumid, title, ( 
     SELECT count(trackid) FROM tracks WHERE tracks.AlbumId = albums.AlbumId ) AS  tracks_count 
     FROM albums 
     ORDER BY tracks_count DESC; 
    
    (це також корельований підзапит)