I know, this is very old question, which is already asked several times.
I want to write query which is better in performance when, we have more than 200 million records, and which should be database independent..
I have tried following queries as
// MYSQL QUERY simillar TO rownum of Oracle (DB Supported: MYSQL, ORACLE, POSTGRESS)
SELECT RS.amt
FROM
(SELECT t.amount AS amt,
@rownum := @rownum + 1 AS rank
FROM salerecord t,
(SELECT @rownum := 0) r
ORDER BY t.amount DESC LIMIT 5) RS
WHERE RS.rank=5
//Works WITH databasases which supports LIMIT, with good performance (DB Supported: MYSQL, Postgres)
SELECT amount FROM salerecord ORDER BY amount DESC LIMIT 4, 1;
//Works WITH almost ALL DATABASES with not having good performance
SELECT amount FROM salerecord a WHERE 5 = (SELECT COUNT(*) FROM salerecord b WHERE a.amount <= b.amount) ;
There is no efficient way to do this in SQL in the absence of LIMIT or TOP operators.
For systems that allow incremental retrieval of results you can simulate the required behaviour by fetching the first five records and simply closing the connection.
Client software built on the .NET framework using LINQ can use the Take operator.
(The above assumes descending ranking on the required dimension per your examples.)