Reputation: 756
I am trying to get only the first row from this query. The query does not return the top row. Here is the query.
SELECT DISTINCT name, age
FROM donates, persons
WHERE name = donor
AND name IN (SELECT receiver FROM donates)
AND ROWNUM <= 1
ORDER BY age DESC;
When I run the query it returns Chirs |35
.
Without the ROWNUM <=1
this is what the table looks like.
NAME | AGE
-------------
george | 62
Chris | 35
zara | 24
Upvotes: 1
Views: 12687
Reputation: 13517
Try to use ROWID
rather than ROWNUM
like this:
SELECT * FROM TABLE_NAME WHERE ROWID = (SELECT MIN(ROWID) FROM TABLE_NAME)
Upvotes: 2
Reputation: 384
You are trying to get the one with minimal age, so I suggest you to use the Min sql built-in function:
SELECT name, Min(age)
FROM donates, persons
WHERE name = donor
AND name IN (SELECT receiver FROM donates)
It is a good practice to avoid rownum. And here you get a more semantic and efficient query.
Hope it helps, Regards
Upvotes: 0
Reputation: 377
I think the best way to get this is to use a subquery as the rownum is being looked at before the order by so:
select * from (
SELECT DISTINCT name, age
FROM donates, persons
WHERE name = donor
AND name IN (SELECT receiver FROM donates)
ORDER BY age DESC
) where ROWNUM <= 1;
For a longer read look at http://www.oracle.com/technetwork/issue-archive/2006/06-sep/o56asktom-086197.html
Upvotes: 3