Sql - Select First 10 Rows Only?
The easiest way to retrieve just the first 10 rows from your query result is to append LIMIT 10
in MySQL, PostgreSQL, and SQLite systems. For SQL Server, it's as simple as adding TOP 10
at the beginning. Use the ORDER BY
clause to ensure sorted and predictable results.
Cross-Platform Examples:
Handling order of rows
Including an ORDER BY
clause becomes crucial when the sequence of the data is essential. You usually need this when working with time-sensitive data or when you want to retrieve the highest or lowest data entities.
This ensures the most recent sales come first, hence returning the most relevant results.
Pagination, ties, and other tricks
We use OFFSET
with FETCH FIRST
for pagination, and when dealing with tied values, FETCH FIRST
will come into play.
Pagination, or resulting data into pages, can be achieved by:
For ties, where values have the same rank, we handle them as follows:
Counting, filtering and joining--in order!
When counting the number of occurrences or joining multiple tables together, remember this: filtering (WHERE) → ordering (ORDER BY) → counting/ joining → then finally selecting the limited rows (LIMIT/ TOP).
Trying to count tags in posts? Make sure you have the most frequent ones!
Joining tables? Ensure accurate matching or else you'll be mixing apples with oranges!
Non-discriminatory database systems
FETCH FIRST
is a modern SQL standard accepted by various DBMS including DB2, PostgreSQL, and Oracle. Each system, however, has its syntax specialities. For instance, in Oracle 12.1 and later, you would:
While in Sybase ASE, the results are limited as follows:
Before LIMIT comes WHERE
Please, before applying LIMIT
, use WHERE
to trim down your dataset. It makes your query more efficient, especially when dealing with big data. Retrieve only the most relevant rows!
Was this article helpful?