Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>First, the query will return the <code>nth</code> <strong>lowest</strong> salary value. To return the <code>nth</code> highest salary value you must change <code>t.sal &lt;= sal</code> to <code>t.sal &gt;= sal</code>.</p> <p>Next, this query works by first finding the distinct list of salary values as one derived table and then determines the number of employees that have a salary less than each one in this list. <code>t.sal &lt;= sal</code> is taking the derived table (which most databases would require have an alias) and comparing each value against the outer <code>emp</code> table. It should be noted that this will return multiple rows in the case of a tie.</p> <p>To manually trace the output, we need some inputs:</p> <pre><code>Alice | 200 Bob | 100 Charlie | 200 Danielle | 150 Select Distinct sal From emp </code></pre> <p>Gives us</p> <pre><code>200 100 150 </code></pre> <p>Now we analyze each row in the outer table</p> <pre><code>Alice - There are 3 distinct salary values less than or equal to 200 Bob - 1 rows &lt;= 100 Charlie - 3 rows &lt;= 200 Danielle - 2 row &lt;= 150 </code></pre> <p>Thus, for each salary value we get the following counts (and reordered by count):</p> <pre><code>Bob 1 Danielle 2 Charlie 3 Alice 3 </code></pre> <p>The most important aspect that I think you are overlooking is that the outer <code>emp</code> table is <em>correlated</em> to the inner count calculation (which is why it is called a correlated subquery). I.e., for each row in the outer <code>emp</code> table, a new count is calculated for that row's salary via <code>t.sal &lt;= sal</code>. Again, most database systems would require the inner most query to have an alias like so (note the <code>As Z</code> alias):</p> <pre><code>Select sal From emp As t Where &amp;n = ( Select Count(Z.sal) From ( Select Distinct sal From emp ) As Z Where t.sal &lt;= Z.sal ) </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload