Here we will see the Oracle Select statement examples to get the top 10 records from a table.
Oracle Select Top 10 Records Using Rownum
You can use the rownum. As soon as Oracle receives the result, it modifies it by adding the rownum column.
After the result has been returned, you need to apply filters to it, and for this, you'll need to use a subquery. Below is an example to get top 10 salaries:
select empno, ename, job, mgr, sal from ( select * from emp order by sal) where rownum <= 10
Oracle SQL Query to Get Top 10 Using Fetch Clause
If you are using Oracle 12c or a later version, you can use the FETCH NEXT N ROWS ONLY
statement. Below is an example:
select empno, ename, job, mgr, sal from emp order by sal fetch next 10 rows only
Output
EMPNO | ENAME | JOB | MGR | SAL |
---|---|---|---|---|
7369 | SMITH | CLERK | 7902 | 800 |
7900 | JAMES | CLERK | 7698 | 950 |
7876 | ADAMS | CLERK | 7788 | 1100 |
7521 | WARD | SALESMAN | 7698 | 1250 |
7654 | MARTIN | SALESMAN | 7698 | 1250 |
7934 | MILLER | CLERK | 7782 | 1300 |
7844 | TURNER | SALESMAN | 7698 | 1500 |
7499 | ALLEN | SALESMAN | 7698 | 1600 |
7782 | CLARK | MANAGER | 7839 | 2450 |
7698 | BLAKE | MANAGER | 7839 | 2850 |
Use Row_Number() Analytical Function To Get Top 10 Records in Oracle
Because ROWNUM
is applied before ORDER BY
, you get an apparently random set. As a result, your query sorts the first ten rows. To find the top ten salaries, use the row_number()
analytic function in a subquery and then filter.
select empno, ename, job, mgr, sal from ( select empno, ename, job, mgr, sal, row_number() over (order by sal) rn from emp order by sal) where rn <= 10
Output
The result will be the same as above.