Useful shortcuts for vi editor

Saturday, 11 October 2014

How to select top 10 records in Oracle 11g and 12c?

In 11g:

As you now that TOP keyword does not exist in 11g, but you can use rownum keyword to query top records.

For example, you want to see top 10 salary records based on employees:

Run that SQL in your editor's SQL window.

Wrong one;
SELECT *
FROM (
 SELECT employee_id, first_name, last_name, salary
 FROM employees
 )
WHERE rownum < 11
ORDER BY salary DESC;

* ORDER BY runs at last so that it should be in sub query.

Correct one;
SELECT *
FROM (
 SELECT employee_id, first_name, last_name, salary
 FROM employees
 ORDER BY salary DESC
 )
WHERE rownum < 11;


In 12c:
With 12c, you may use special syntax to see top records that is "FETCH" syntax.

SELECT employee_id, first_name, last_name, salary
FROM employees
ORDER BY salary DESC
FETCH FIRST 10 ROWS ONLY;

Also, you may disregard first 5 records inside 10 records.

SELECT employee_id, first_name, last_name, salary

FROM employees
ORDER BY salary DESC
OFFSET 5 ROWS 
FETCH NEXT 5 ROWS ONLY;

That's all. Bye :)