0

I am trying with MySQL/SQL Queries and learning tutorials for complicated Queries.

Below is a Query which runs well as mentioned but the result set is not understandable.

The Query retrieves "2" highest paid employees FROM each Department.

SELECT deptno, empno, sal
FROM emp e
WHERE
2 > ( SELECT COUNT(e1.sal)
      FROM emp e1
      WHERE e.deptno = e1.deptno AND e.sal < e1.sal )
ORDER BY 1,3 DESC; 

But I am not able to understand what this 2 > and Order by 1,3 does in the query.?

So as to understand the query I have run the WHERE Cause Query separately as follows:

SELECT COUNT(e1.sal)
          FROM emp e1
          WHERE e.deptno = '1';

The above query returned me the count of deptno with value '1'.

So it means each departments will be counted!!

I am not sure what exactly happens in e.sal < e1.sal ?? Is it running recursively?? to calculate the highest paid employees??

Can some one help me in understanding the query!

If I can understand the above logic I can understand the logic of the query below:

4th Top Salary of all the employees:

SELECT DEPTNO, ENAME, SAL
FROM EMP A
WHERE
3 = (SELECT COUNT(B.SAL) FROM EMP B
WHERE A.SAL < B.SAL) ORDER BY SAL DESC;

Sorry for not providing a Fiddle..

1 Answer 1

1

This is a query with a correlated subquery.

To better understand what subquery is doing you can move it to the outer select and take a look at what it returns

SELECT deptno, empno, sal,
      ( SELECT COUNT(e1.sal)
          FROM emp e1
         WHERE e.deptno = e1.deptno AND e.sal < e1.sal ) rank
FROM emp e

Sample output:

| DEPTNO | EMPNO | SAL | RANK |
-------------------------------
|      1 |   103 |  30 |    0 |
|      1 |   102 |  20 |    1 |
|      1 |   101 |  10 |    2 |
|      2 |   201 | 100 |    0 |
|      2 |   203 |  50 |    1 |
|      2 |   202 |  40 |    2 |

Here is SQLFiddle demo

What it does it returns (for each record in the outer select) a number of rows with the same department where salary is less then salary of the row being retrieved in outer select thus ranking records in every department based on salary.

Now WHERE 2 > (subquery) which is the same as WHERE (subquery) < 2 filters out rows with rank higher then 1 effectively implementing TOP 2 rule.

ORDER BY 1, 3 DESC is the same as ORDER BY deptno, sal DESC. 1 and 3 are positions of deptno and sal columns in select clause.

2
  • Will the subQuery works recursively ??? in e.sal < e1.sal.. There is my confusion..
    – DonOfDen
    Jul 25, 2013 at 10:38
  • 1
    No, not recursively. It takes one row in outer select. Then executes inner select using values (e.deptno, e.sal) from outer select and use them as parameters in where clause of inner select. And do that for every row in emp table.
    – peterm
    Jul 25, 2013 at 10:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.