Search code examples
sqloraclegreatest-n-per-group

How to show only first result from select?


I'm trying to show only first result from this select, but cant figure out how to do it or what function should I use.

I have tried rownum <= 1, but it changed shown result.

select name || ' ' || surname as meno, role
from system_user
order by surname ASC
;

Solution

  • In Oracle, you need to use a subquery:

    select su.*
    from (select name || ' ' || surname as meno, role
          from system_user
          order by surname ASC
         ) su
    where rownum = 1;
    

    The most recent versions of Oracle (12C) make this simpler by supporting the ANSI standard FETCH FIRST 1 ROW ONLY syntax:

    select name || ' ' || surname as meno, role
    from system_user
    order by surname ASC
    fetch first 1 row only;