-1
SELECT * FROM workers ORDER BY salary DESC LIMIT 2;

I have this SQL statement to get the salary of the two best paid workers but I'm getting a SQL command was not ended correctly.

EDITED:

SELECT  worker_id, last_name, job_id, salary
    FROM (SELECT w.*,
                rank() over (ORDER BY w.salary desc) rnk
          FROM worker w
         )
   WHERE rnk <= 5;
sqlhelp12
  • 1
  • 2
  • Welcome to [so]! The [code you added](https://stackoverflow.com/revisions/62516758/3) looks much like the code suggested in [an answer](https://stackoverflow.com/a/62516789/711006). If this is the solution, please [mark the answer accepted](http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work), see [What should I do when someone answers my question?](https://stackoverflow.com/help/someone-answers). If you are asking about the pasted code, please [edit] to clarify the question. – Melebius Jun 23 '20 at 08:51

2 Answers2

0

If your database doesn't support LIMIT clause, do it differently. For example:

select *
from (select w.*,
             rank() over (order by w.salary desc) rnk
      from workers w
     )
where rnk <= 2;

For example (based on Scott's EMP table):

SQL> select empno, job, sal from emp order by sal desc;

     EMPNO JOB              SAL
---------- --------- ----------
      7839 PRESIDENT       5000      --> two 
      7902 ANALYST         3000      --> highest
      7788 ANALYST         3000      --> salaries (5000 and 3000)
      7566 MANAGER         2975
      7698 MANAGER         2850
      7782 MANAGER         2450
      7499 SALESMAN        1600
      7844 SALESMAN        1500
      7934 CLERK           1300
      7521 SALESMAN        1250
      7654 SALESMAN        1250
      7876 CLERK           1100
      7369 CLERK           1000
      7900 CLERK            950

14 rows selected.

SQL> select *
  2  from (select w.*,
  3              rank() over (order by sal desc) rnk
  4        from emp w
  5       )
  6  where rnk <= 2;

     EMPNO ENAME      JOB              MGR HIREDATE          SAL       COMM     DEPTNO        RNK
---------- ---------- --------- ---------- ---------- ---------- ---------- ---------- ----------
      7839 KING       PRESIDENT            11/17/1981       5000                    10          1
      7788 SCOTT      ANALYST         7566 12/09/1982       3000                    20          2
      7902 FORD       ANALYST         7566 12/03/1981       3000                    20          2

SQL>
Littlefoot
  • 78,293
  • 10
  • 26
  • 46
0

Oracle doesn't support limit. Use;

select w.*
from workers w
order by salary desc
fetch first 2 rows only;

This works in the most recent versions of Oracle. In earlier versions, you can use a subquery:

select w.*
from (select w.*
      from workers w
      order by salary desc
     ) w
where rownum <= 2;
Gordon Linoff
  • 1,122,135
  • 50
  • 484
  • 624