Nth Highest Salary from EMP table , need explaination

I am new to the database world and hence learning queries at the initial stages. I want to retrieve the nth highest salary from the EMP table. I was not able to find out the answer by myself , so I searched on google. The following was the answer i got :
SELECT DISTINCT (a.sal) FROM EMP A WHERE &N = (SELECT COUNT (DISTINCT (b.sal)) FROM EMP B WHERE a.sal<=b.sal);
Enter value for n: 2
SAL
3700
Suppose the table contains salary in the following order :
SAL
2000
3000
3700
4000
3700
2000
So how come I will get the correct answer with the abov query ? I am not able to understand the part --- WHERE &N = (SELECT COUNT (DISTINCT (b.sal)) FROM EMP B WHERE a.sal<=b.sal);
Specially the condition WHERE a.sal<=b.sal is very confusing to me. Can anyone help me please to understand the same.

user12328699 wrote:
I am new to the database world and hence learning queries at the initial stages. I want to retrieve the nth highest salary from the EMP table. I was not able to find out the answer by myself , so I searched on google. The following was the answer i got :
SELECT DISTINCT (a.sal) FROM EMP A WHERE &N = (SELECT COUNT (DISTINCT (b.sal)) FROM EMP B WHERE a.sal<=b.sal);
Enter value for n: 2
SAL
3700
Suppose the table contains salary in the following order :
SAL
2000
3000
3700
4000
3700
2000
So how come I will get the correct answer with the abov query ? I am not able to understand the part --- WHERE &N = (SELECT COUNT (DISTINCT (b.sal)) FROM EMP B WHERE a.sal<=b.sal);
Specially the condition WHERE a.sal<=b.sal is very confusing to me. Can anyone help me please to understand the same.There is many better way to get the nth highest salary
But still if you want to understand the same.
Assuming the data is sorted in ascending order, then
1) a.sal=2000, so a.sal<=b.sal results in count as 3 (not equal to user input)
2) a.sal=3700, so a.sal<=b.sal results in count as 2 (equal to user input)
3) a.sal = 4000 , so a.sal<=b.sal results in count as 1 (not equal to user input)
Hence the answer is 3700
Regards
Anurag

Similar Messages

  • Nth highest Salary.

    I need a well tuned query to find the nth highest salary from emp table.
    I have one but no idea if it is tuned one.
    select min(sal) from (select sal,rownum from (select sal from (select distinct sal from emp order by sal desc)) where rownum <=n) ;

    You can use analytic functions.
    select *
      from (
    select e.*, row_number() over(order by sal desc nulls last) rno
      from emp e
    where rno = 5 --<<-- replace 5 with N
    I need a well tuned query to find the nth highest salary from emp table.This totally depends on how you have setup your database.

  • Retrive the second-highest value from the table using query.

    Hi,
    I am using Oracle 8i...
    I have to retrieve the second-highest salary from the table...for this I need to write a SQL..Can anybody please help me to figure out this problem..Thanks in advance..
    smitha

    Using analytic functions
    SELECT *
    FROM (SELECT other_columns,DENSE_RANK() OVER(ORDER BY salary DESC) sal_rank
          FROM table)
    WHERE sal_rank = 2
    Using Order by and rownum
    SELECT *
    FROM (SELECT other_columns,rownum sal_rank
          FROM (SELECT other_columns,salary
                FROM table
                ORDER BY salary DESC))
    WHERE sal_rank = 2TTFN
    John

  • How to find the third highest salary from deptno20,from employee table

    how to find the third highest salary from deptno20,from employee table

    SELECT *
      FROM emp;
    EMPNO
    ENAME
    JOB
    MGR
    HIREDATE
    SAL
    COMM
    DEPTNO
    7369
    SMITH
    CLERK
    7902
    12/17/1980
    1000
    3
    20
    7499
    FEDERAL
    SALESMAN
    7654
    2/20/1981
    2000
    4
    30
    7521
    WARD
    SALESMAN
    7698
    2/22/1981
    3000
    4
    30
    7566
    JONES
    MANAGER
    7839
    4/2/1981
    4000
    3
    20
    7839
    MARTIN
    SALESMAN
    7698
    9/28/1981
    5421
    4
    30
    7698
    BLAKE
    MANAGER
    7698
    5/1/1981
    6222
    4
    30
    7782
    CLARK
    MANAGER
    7839
    6/9/1981
    5222
    2
    10
    7788
    SCOTT
    ANALYST
    7566
    12/9/1982
    5463
    3
    20
    7839
    KING
    PRESIDENT
    7902
    11/17/1981
    8543
    2
    10
    7844
    TURNER
    SALESMAN
    7698
    9/8/1981
    2124
    4
    30
    7876
    ADAMS
    CLERK
    7788
    1/12/1983
    2125
    3
    20
    7900
    JAMES
    CLERK
    7698
    12/3/1981
    5462
    4
    30
    7902
    FORD
    ANALYST
    7566
    12/3/1981
    2132
    3
    20
    7934
    MILLER
    CLERK
    7782
    1/23/1982
    5165
    2
    10
    SELECT sal, deptno
      FROM (SELECT   a.*,
                     DENSE_RANK () OVER (PARTITION BY deptno ORDER BY sal DESC) r
                FROM emp a
          ----  ORDER BY sal DESC
    WHERE r = 3;
    SAL
    DEPTNO
    5421
    30
    5165
    10
    2132
    20
    Regards ,
    Friend
    Message was edited by: MostWanted!!!!

  • Finding nth highest salary

    Hi guys , I am trying to find the nth highest salary
    using the below query , is there any case in which the below query can fail
    select
    * from (
    select
    distinct rownum rn,salary from emp_mgr order by rownum) t where t.rn=3

    chris227 wrote:
    Sory, may be i am blind, dont see it yet.
    Doesnt the Nth high paid employee earns the Nth highest salary?
    No. Multiple employees can earn same salary. Look at EMP table:
    SQL> select ename,sal from emp order by sal desc;
    ENAME             SAL
    KING             5000
    FORD             3000
    SCOTT            3000
    JONES            2975
    BLAKE            2850
    CLARK            2450
    ALLEN            1600
    TURNER           1500
    MILLER           1300
    WARD             1250
    MARTIN           1250
    ENAME             SAL
    ADAMS            1100
    JAMES             950
    SMITH             800
    Highest salary 5000. Second highest salary is 3000. Third highest salary is 2975. Now look what NTH_VALUE returns:
    SQL> select distinct sal
      2    from (select nth_value(sal,&n) over(order by sal desc) sal from emp)
      3  /
    Enter value for n: 1
    old   2:   from (select nth_value(sal,&n) over(order by sal desc) sal from emp)
    new   2:   from (select nth_value(sal,1) over(order by sal desc) sal from emp)
           SAL
          5000
    SQL> /
    Enter value for n: 2
    old   2:   from (select nth_value(sal,&n) over(order by sal desc) sal from emp)
    new   2:   from (select nth_value(sal,2) over(order by sal desc) sal from emp)
           SAL
          3000
    SQL> /
    Enter value for n: 3
    old   2:   from (select nth_value(sal,&n) over(order by sal desc) sal from emp)
    new   2:   from (select nth_value(sal,3) over(order by sal desc) sal from emp)
           SAL
          3000
    SQL> /
    Enter value for n: 4
    old   2:   from (select nth_value(sal,&n) over(order by sal desc) sal from emp)
    new   2:   from (select nth_value(sal,4) over(order by sal desc) sal from emp)
           SAL
          2975
    SQL>
    SY.

  • Fetching ename who are all having max(sal) in each of job from emp table

    hi all,
    i need a query to fetch all the ename who are all having maximum salary in each job category from emp table
    thankx in advance
    regrds,
    punith

    SQL> select ename,job,sal
      2  from emp
      3  order by job,sal desc;
    ENAME      JOB              SAL
    SCOTT      ANALYST         3000
    FORD       ANALYST         3000
    MILLER     CLERK           1300
    ADAMS      CLERK           1100
    JAMES      CLERK            950
    SMITH      CLERK            800
    JONES      MANAGER         2975
    BLAKE      MANAGER         2850
    CLARK      MANAGER         2450
    KING       PRESIDENT       5000
    ALLEN      SALESMAN        1600
    TURNER     SALESMAN        1500
    WARD       SALESMAN        1250
    MARTIN     SALESMAN        1250
    14 rows selected.
    SQL> select ename,job,sal from emp
      2  where sal in(select distinct max(sal) from emp
      3* group by job)
    SQL> /
    ENAME      JOB              SAL
    FORD       ANALYST         3000
    SCOTT      ANALYST         3000
    MILLER     CLERK           1300
    JONES      MANAGER         2975
    KING       PRESIDENT       5000
    ALLEN      SALESMAN        1600
    6 rows selected.
    SQL>Is this what you need ?

  • Getting cummulative sum of salaries of employees from emp table

    Hi gurus,
    Can any body tell me how to get cummulative sum of salaries of employees in emp table by using analytical functions.
    thanks in advance....

    SeánMacGC wrote:
    Hello,
    Try:
    SELECT empno,
    SUM(SAL) OVER () cumulative_sal
    FROM emp;
    You need to order by to get the cumulative salary
    SQL> SELECT empno,
      2     SUM(SAL) OVER () cumulative_sal
      3    FROM emp;
         EMPNO CUMULATIVE_SAL
          7369          29025
          7499          29025
          7521          29025
          7566          29025
          7654          29025
          7698          29025
          7782          29025
          7788          29025
          7839          29025
          7844          29025
          7876          29025
         EMPNO CUMULATIVE_SAL
          7900          29025
          7902          29025
          7934          29025
    14 rows selected.
    SQL> SELECT empno, sal,
      2     SUM(SAL) OVER (Order by empno) cumulative_sal
      3    FROM emp;
         EMPNO        SAL CUMULATIVE_SAL
          7369        800            800
          7499       1600           2400
          7521       1250           3650
          7566       2975           6625
          7654       1250           7875
          7698       2850          10725
          7782       2450          13175
          7788       3000          16175
          7839       5000          21175
          7844       1500          22675
          7876       1100          23775
         EMPNO        SAL CUMULATIVE_SAL
          7900        950          24725
          7902       3000          27725
          7934       1300          29025
    14 rows selected.

  • How to get second maximum salary from employee table(sql query)

    how to get second maximum salary from employee table(sql query)

    dude there is no matter of structure .........that user already said its from employee table ...............its basic table in sql and there is no need to specify the table structure
    .........i think u got my point I think you are the one who didn't understand Sarma's point.
    Give a man a fish and you feed him once. Teach a man how to fish and you feed him a life long.
    >
    and the query is
    select max(sal) from emp where sal<(select max(sal)
    from emp);
    this will give the 2nd max salary from the emp tableBtw: You solution is bad, because it needs to scan and sort the table emp twice. And a better solution has been given already.
    Message was edited by:
    Sven W. - reordered statements

  • I need to add a single field from with_item table . need to write select query with reference to company code , account doc no , fiscal year

    I need to add a single field from with_item table . need to write select query with reference to company code , account doc no , fiscal year

    Hi Arun ,
    Can you explain little bit more ??
    what is account doc no? 
    what are the transactions should be displayed in your output??
    -Rajesh N

  • To find the lowest salary from a table

    hello guys,
    i need to find the lowest salary from a table. whats the easy way to do this.

    How do you handle ties?
    If you want multiple rows returned when there are multiple people with the same salary
    SELECT *
      FROM(
        SELECT a.*,
               rank() over (order by salary desc ) rnk
          FROM your_table a)
    WHERE rnk = 1If you want to handle ties differently, use a different analytic function. Probably dense_rank or row_number.
    Justin

  • How can i get first four highest values from a table

    suppose we have salary table and we need first 4 highest salaries in one query or attemp

    Or use an analytic:
    SQL> select ename, sal from emp;
    ENAME                       SAL
    SMITH                       800
    ALLEN                      1600
    WARD                       1250
    JONES                      2975
    MARTIN                     1250
    BLAKE                      2850
    CLARK                      2450
    SCOTT                      3000
    KING                       5000
    TURNER                     1500
    ADAMS                      1100
    JAMES                       950
    FORD                       3000
    MILLER                     1300
    14 rows selected.
    SQL> select ename, sal
      2  from
      3  (
      4     select ename
      5           ,sal
      6           ,dense_rank() over (order by sal desc) dr
      7     from   emp
      8  )
      9  where dr <= 4;
    ENAME                       SAL
    KING                       5000
    SCOTT                      3000
    FORD                       3000
    JONES                      2975
    BLAKE                      2850

  • To find 2nd highest salary in employee table

    Hi,
    I want to know how to calculate the 2nd highest salaried employee details.
    rownum "=" sign cannot be used i suppose and
    with and without using orderby clause.
    both the methods needed.
    cheers,

    With order by
    select * from
       ( select q.*, rownum as rn from
          ( select * from emp order by sal desc ) q
    where rn=2
    /With analytics:
    select empno , sal
    from ( select empno , sal
                  , dense_rank () over (order by sal desc) as sal_rank
           from emp )
    where sal_rank = 2Notice that DENSE_RANK() might give us a different result compared to RANK() and both give us a different result from the first example.
    Cheers, APC

  • How to find top three salary of emp table?

    Hi,
    I am trying to get top 3 salaries using MAX() in sql but it is only showing 1 row not 3.The following qury showing only the 3rd highest.
    SELECT MAX(Sal) ThirdHighest FROM emp
    WHERE Sal < (SELECT MAX(Sal) FROM emp
    WHERE Sal =(SELECT MAX(Sal) FROM emp
    WHERE Sal <(SELECT MAX(Sal) FROM emp)))
    I dont want to use the following method.
    SELECT department_id dept, first_name || ' ' || last_name name, salary
    FROM (
    SELECT department_id, first_name, last_name,
    MAX(salary) OVER (PARTITION BY department_id) dept_max_sal, salary
    FROM employees e
    ) WHERE salary = dept_max_sal;
    Kindly help to create query using only "max()" for top 3 salaries.

    947459 wrote:
    Hi,
    I am trying to get top 3 salaries using MAX() in sql but it is only showing 1 row not 3.The following qury showing only the 3rd highest.
    SELECT MAX(Sal) ThirdHighest FROM emp
    WHERE Sal < (SELECT MAX(Sal) FROM emp
    WHERE Sal =(SELECT MAX(Sal) FROM emp
    WHERE Sal <(SELECT MAX(Sal) FROM emp)))
    I dont want to use the following method.
    SELECT department_id dept, first_name || ' ' || last_name name, salary
    FROM (
    SELECT department_id, first_name, last_name,
    MAX(salary) OVER (PARTITION BY department_id) dept_max_sal, salary
    FROM employees e
    ) WHERE salary = dept_max_sal;
    Kindly help to create query using only "max()" for top 3 salaries.Why? Why not use what Oracle provides for doing top N queries?
    SQL> ed
    Wrote file afiedt.buf
      1  select empno, ename, sal
      2  from (
      3        select empno, ename, sal, dense_rank() over (partition by 1 order by sal desc) as r from emp
      4       )
      5* where r <= 3
    SQL> /
         EMPNO ENAME             SAL
          7839 KING             5000
          7788 SCOTT            3000
          7902 FORD             3000
          7566 JONES            2975Using just the MAX function alone will make it harder for you and is completely unnecessary.

  • How to get the select * from emp table output on the console  using java

    public class software {
          * @param args
         static final String JDBC_DRIVER = "oracle.jdbc.driver.OracleDriver";
         static final String DATABASE_URL = "jdbc:oracle:abc";
         private static Connection connection;
         private static Statement statement;
         public static void main(String[] args) {
              // TODO Auto-generated method stub
         try {
              System.out.println("-------THIS IS THE Class.forNameJDBC_DRIVER");
                   Class.forName(JDBC_DRIVER);
                   System.out.println("THIS IS THE Class.forNameJDBC_DRIVER");
                   connection = DriverManager.getConnection(DATABASE_URL, "abc",
                   "abc");
                   System.out.println("THIS IS THE connection abc ,abc");
                   statement = connection.createStatement();
                   //Query to find the values in the EMP table.
                   ResultSet resultSet = statement.executeQuery("SELECT * from EMP");
                   if(resultSet.next()){
                   System.out.println("THESE ARE THE VALUES IN EMP TABLE:"+resultSet);  /// How can i get all the values record wise on the  console ??????
                   resultSet.close();
         catch (ClassNotFoundException classNotFound) {
                   System.out.println("Driver not Found"+classNotFound.getMessage());
              } catch (SQLException sqlException) {
                   System.out.println("SQL Exception - bad sql");
                   System.out.println(sqlException.getMessage());
    }

    1sai
    Please assign the dukes here and in your previous threads.
    See [http://wikis.sun.com/display/SunForums/Duke+Stars+Program+-+How+it+Works]
    You are currently the all time career leader in un-awarded dukes, with including this thread 75 unawarded dukes for questions you marked as answered.
    It's even worse when you look and see that you have awarded many dukes as well. So you do know how to do it. You're just too lazy and rude to be bothered.
    Don't be a lazy wank.

  • How to display required data from emp table?

    Hi every one, this is my first post in this portal. I want display the details of emp table.. for that I am using this SQL statement.
    select * from emp where mgr=nvl(:mgr,mgr);
    when I give the input as 7698 it is displaying the corresponding records... and also when I won't give any input then it is displaying all the records except the mgr with null values.
    1)I want to display all the records when I won't give any input including nulls
    2)I want to display all the records who's mgr is null
    Is there any way to incorporate to include all these in a single query..

    Hi,
    937440 wrote:
    Hi every one, this is my first post in this portal. Welcome to the forum!
    Be sure to read the forum FAQ {message:id=9360002}
    I want display the details of emp table.. for that I am using this SQL statement.
    select * from emp where mgr=nvl(:mgr,mgr);
    when I give the input as 7698 it is displaying the corresponding records... and also when I won't give any input then it is displaying all the records except the mgr with null values.
    1)I want to display all the records when I won't give any input including nulls
    2)I want to display all the records who's mgr is null
    Is there any way to incorporate to include all these in a single query..It's a little unclear what you're asking.
    The following query always includes rows where mgr is NULL, and when the bind variable :mgr is NULL, it displays all rows:
    SELECT  *
    FROM     emp
    WHERE     LNNVL (mgr != :mgr)
    ;That is, when :mgr = 7698, it displays 6 rows, and when :mgr is NULL it displays 14 rows (assuming you're using the Oracle-supplied scott.emp table).
    The following query includes rows where mgr is NULL only when the bind variable :mgr is NULL, in which case it displays all rows:
    SELECT     *
    FROM     emp
    WHERE     :mgr     = mgr
    OR       :mgr       IS NULL
    ;When :mgr = 7698, this displays 5 rows, and when :mgr is NULL it displays 14 rows.
    The following query includes rows where mgr is NULL only when the bind variab;e :mgr is NULL, in which case it displays only the rows where mgr is NULL. That is, it treats NULL as a value:
    SELECT     *
    FROM     emp
    WHERE     DECODE ( mgr
                , :mgr, 'OK'
                )     = 'OK'
    ;When :mgr = 7698, this displays 5 rows, and when :mgr is NULL, it displays 1 row.

Maybe you are looking for

  • Xml publisher report giving warning

    Hi friends, I have a issue with xml publisher report. All existing xml publisher reports are working fine. Only the problem is newly created one. Application version 11.5.10.2 dDtabase 9i BIdesktop version is 10.1.3.4.1 MS office  2010 i checked the

  • Ipod Touch Stops Syncing

    Okay so after making a backup and restoring my Ipod touch, I was working on getting the backup back into it. It goes on smoothly until it runs into one song and then stops completely, freezing Itunes and after a while my computer until the error that

  • Loading wave file data into array

    Greetings For starters, I'm still learning java, so forgive me if this is a trivial question. I've been using the documentation on the java sound api as a guide. What I am trying to do is to load a wav file data into a byte array and eventually I wil

  • Problem with temporary table in stored procedure

    Hi, I have to execute a stored procedure in java , where the stored procedure has refcursor as out parameter and within the procedure the refcursor out parameter is populated from a temporary table when iam trying to get the resultset in my program i

  • Question about content provider having access to code view

    can they? i have read and read to try and figure this out. i don't want to offer my client something that doesn't exist. if i set up her site with contribute, she buys her version, and we get it all working, can she access the html code to add paypal