Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select top five or 'N' rows in Oracle 11g [duplicate]

select distinct ani_digit, ani_business_line from cta_tq_matrix_exp limit 5

I want to select top five rows from my resultset. if I used above query, getting syntax error.

like image 424
Karthikeyan Sukkoor Avatar asked Dec 18 '13 11:12

Karthikeyan Sukkoor


People also ask

WHAT IS TOP-N in Oracle?

Top-N queries provide a method for limiting the number of rows returned from ordered sets of data. They are extremely useful when you want to return the top or bottom "N" number of rows from a set or when you are paging through data.

Which SQL keyword is used to do ranking in top-n analysis?

SQL Server SELECT TOP Clause – TOP-N Analysis You can use the keyword PERCENT to receive a certain percentage of the data, rather than an arbitrary number of rows. The following example returns the top 10 percent earners in the company.


3 Answers

You'll need to use DISTINCT before you select the "top 5":

SELECT * FROM 
(SELECT DISTINCT ani_digit, ani_business_line FROM cta_tq_matrix_exp) A
WHERE rownum <= 5
like image 173
D Stanley Avatar answered Oct 28 '22 20:10

D Stanley


LIMIT clause is not available in Oracle.

Seeing your query, you seem to be interested only in a certain number of rows (not ordered based on certain column value) and so you can use ROWNUM clause to limit the number of rows being returned.

select distinct ani_digit, ani_business_line from cta_tq_matrix_exp WHERE rownum <= 5

If you want to order the resultset and then limit the number of rows, you can modify your query as per the details in the link provided by Colin, in the comments above.

like image 32
Incognito Avatar answered Oct 28 '22 19:10

Incognito


  select distinct ani_digit, ani_business_line from cta_tq_matrix_exp where rownum<=5;
like image 3
Sai Avatar answered Oct 28 '22 20:10

Sai