Difference between revisions of "SELECT .. SELECT"

From SQLZOO
Jump to: navigation, search
Line 37: Line 37:
 
==Correlated Subquery==
 
==Correlated Subquery==
 
<div class='qu'>If a value from the outer query appears in the inner query this is "correlated subquery".
 
<div class='qu'>If a value from the outer query appears in the inner query this is "correlated subquery".
<p class='imper'>Show the countries where the population is greater than average for its region</p>
+
<p class='imper'>Show the countries where the population is greater than 5 times the average for its region</p>
  
 
<source lang='sql' class='def'>
 
<source lang='sql' class='def'>
 
SELECT name
 
SELECT name
 
   FROM bbc b1
 
   FROM bbc b1
  WHERE population>
+
  WHERE population>  
   (SELECT AVG(population) FROM bbc
+
   5*(SELECT AVG(population) FROM bbc
    WHERE region=b1.region)
+
    WHERE region=b1.region)
 
</source>
 
</source>
 
</div>
 
</div>

Revision as of 01:22, 9 August 2012

Contents

Subquery Table, Derived Tables, Nested Queries

You can use the results from one query in another query

Subquery with FROM

You may use a SELECT statement in the FROM line.

In this case the derived table X has columns name and gdp_per_capita. The calculated values in the inner SELECT can be used in the outer SELECT.

SELECT name, ROUND(gdp_per_capita)
  FROM
  (SELECT name,
          gdp/population AS gdp_per_capita
     FROM bbc) X
 WHERE gdp_per_capita>20000

Notice that

  • the inner table is given an alias X
  • the first column in the inner query keeps its name
  • the second column in the inner query has an alias

Subquery with IN

Find the countries in the same region as Bhutan

You may use a SELECT statement in the WHERE line - this returns a list of regions.

SELECT name
  FROM bbc
 WHERE region IN
  (SELECT region FROM bbc
    WHERE name='Bhutan')

Correlated Subquery

If a value from the outer query appears in the inner query this is "correlated subquery".

Show the countries where the population is greater than 5 times the average for its region

SELECT name
  FROM bbc b1
 WHERE population> 
  5*(SELECT AVG(population) FROM bbc
     WHERE region=b1.region)


See also:
Personal tools
Namespaces

Variants
Actions
Reference
Toolbox
Google AdSense