Search This Blog

Oracle / PLSQL: Retrieve Top N records from a query

oracle PL/SQL


Oracle / PLSQL: Retrieve Top N records from a query


Question: How can I retrieve the Top N records from a query?

For example, what if I wanted to retrieve the first 3 records from my query results. How can I do this?

Answer: To retrieve the Top N records from a query, you can use the following syntax:

SELECT *
FROM (your ordered query) alias_name
WHERE rownum <= Rows_to_return
ORDER BY rownum;

For example, if you wanted to retrieve the first 3 records from the suppliers table, sorted by supplier_name in ascending order, you would run the following query: