Skip to Main Content
  • Questions
  • Query ask in Interview - fetch first three rows

Breadcrumb

Question and Answer

Chris Saxon

Thanks for the question, Abhijit.

Asked: March 15, 2016 - 11:45 am UTC

Last updated: March 17, 2016 - 2:17 am UTC

Version: 11g

Viewed 1000+ times

You Asked

How to print First Three records of table without using rownum and rowid?

and Chris said...

Pre-12c you can use the analytic function row_number():

select *
from   (
  select t.*, row_number() over (order by cols) rn
  from   t
)
where  rn <= 3;


12c onwards it gets even easier with the fetch first syntax:

select * 
from   t
order  by cols
fetch  first 3 rows only;


Tom discusses these in more detail at

http://www.oracle.com/technetwork/issue-archive/2007/07-jan/o17asktom-093877.html

And fetch first at:

http://www.oracle.com/technetwork/issue-archive/2013/13-sep/o53asktom-1999186.html

Rating

  (2 ratings)

Is this answer out of date? If it is, please let us know via a Comment

Comments

Thanks for response

abhu, March 16, 2016 - 11:47 am UTC

I tried ur solution . Its working properly.

It's a trick question

Jeff, March 16, 2016 - 6:04 pm UTC

It's a trick question - how do they define the "first" rows in a table"?


Chris Saxon
March 17, 2016 - 2:17 am UTC

fair point

More to Explore

Analytics

Analytic SQL got you confused? Check out Connor McDonald's complete video course.