0

I want to find the city and length of city (i.e. number of characters in the word CITY) where the length of city is maximum in the table. In case, we have more than one value we have to take only the first value on the basis of alphabetical arrangement of the city.

There is a weird thing I observe:

SELECT CITY, LENGTH(CITY) FROM STATION ORDER BY LENGTH(CITY) DESC, CITY;

gives me the correct table with the desired output as the first row with Length(City) = 21. But, when I try to retrieve the first row using

SELECT CITY, LENGTH(CITY) FROM STATION WHERE ROWNUM = 1 ORDER BY LENGTH(CITY) DESC, CITY;

query in Oracle it gives me some other row which has Length(City) = 12.

Please help me understand what is going wrong! Also FYI, there is just one value with maximum length of city.

Amit Pathak
  • 1,145
  • 11
  • 26

3 Answers3

4

The WHERE clause of your query is executed before ORDER BY so the ROWNUM = 1 is not the expected row. You can use FETCH FIRST ROW ONLY instead:

SELECT CITY, LENGTH(CITY) 
FROM STATION 
ORDER BY LENGTH(CITY) DESC, CITY 
FETCH FIRST ROW ONLY;

... or you put the statement in a sub-select and use WHERE with ROWNUM on this:

SELECT * 
FROM (
  SELECT CITY, LENGTH(CITY) 
  FROM STATION 
  ORDER BY LENGTH(CITY) DESC, CITY
)x WHERE ROWNUM = 1;

demo on dbfiddle.uk

Sebastian Brosch
  • 42,106
  • 15
  • 72
  • 87
4

rownum works just fine. The where clause is processed before the order by. You can use a subquery instead:

SELECT S.*
FROM (SELECT CITY, LENGTH(CITY)
      FROM STATION S
      ORDER BY LENGTH(CITY) DESC, CITY
     ) S
WHERE ROWNUM = 1 ;

Or, better yet, use FETCH which has been available in Oracle for many years:

SELECT CITY, LENGTH(CITY)
FROM STATION S
ORDER BY LENGTH(CITY) DESC, CITY
FETCH FIRST 1 ROW ONLY;
Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786
2

You can also do it like this:

select city, length_city
from ( SELECT CITY
              , LENGTH(CITY) length_city
              , row_number() over(order by LENGTH(CITY) DESC, CITY) rn
       FROM STATION)
where rn =1;

Here is a small DEMO

VBoka
  • 8,995
  • 3
  • 16
  • 24
  • Hi @AmitPathak, it would be nice to get your feedback. You can accept the correct answer and comment if some of the answers is not ok so we can know why is not ok and then try to help more... Cheers! – VBoka Jan 26 '20 at 12:55
  • Hi @VBoka can you please explain the **over** keyword you used – Amit Pathak Mar 05 '20 at 08:23
  • 1
    Hi @AmitPathak here is what I have found so I can answer you fast and helpful: https://stackoverflow.com/questions/1092120/over-clause-in-oracle Please do tell if it is not enough – VBoka Mar 05 '20 at 08:39