In SQL Server, TOP may be used to return the first n number of rows in a query. For example,
SELECT TOP 100 * FROM users ORDER BY idmight be used to return the first 100 people that registered for a site. (This is not necessarily the best way, I am just using it as an example).
My question is - What is the equivalent to TOP in other databases, such as Oracle, MySQL, PostgreSQL, etc? If there is not an equivalent keyword, what workarounds can you recommend to achieve the same result?
In SQL Anywhere, it's the same as SQL Server:
You can even start in the middle of the result set if you want:
gets the 50th through 150th rows of the result set.
You can use RANK() and DENSE_RANK() in Oracle. Here is a link to AskTom website explaining how to to pagination and top-n queries with DENSE_RANK in Oracle.
For Postgres and MySQL it's the LIMIT keyword.
To select first
100
rows:MySQL
andPostgreSQL
:Oracle
:Note that you need a subquery here. If you don't add a subquery,
ROWNUM
will select first10
rows in random order and then sort them bycolumn
.To select rows between
100
and300
:MySQL
:PostgreSQL
:Oracle
:Note that an attempt to simplify it with
ROWNUM BETWEEN 100 AND 200
(as opposed torn BETWEEN 100 AND 200
in the outer query) will return nothing inOracle
!RN BETWEEN 100 AND 200
will work inOracle
too but is less efficient.See the article in my blog for performance details:
as in
Oracle:
With a nice explanation on how to make it work in AskTom.
In Ingres the same query would by:
Ingres question was already answered in StackOverflow before.