Sql Query To Select Last 10 Records

7 min read

Selecting the most recent entries from a database table is a fundamental operation for developers, data analysts, and database administrators. Whether you are building a dashboard that displays the latest user activity, debugging a recent transaction error, or generating a report on the newest inventory arrivals, knowing how to write a SQL query to select last 10 records efficiently is essential. The approach varies slightly depending on the specific database management system (DBMS) you are using, but the core logic remains consistent: define a sort order based on a timestamp or an auto-incrementing identifier, and then limit the result set Simple as that..

Easier said than done, but still worth knowing.

Understanding the Core Concept: Ordering and Limiting

Before diving into syntax variations, it is crucial to understand that SQL tables represent unordered sets of data by definition. There is no inherent "last" record unless you impose an order. So naturally, to reliably retrieve the last 10 records, you must have a column that defines the sequence. This is typically a created_at timestamp, an updated_at timestamp, or an auto-incrementing primary key id.

The standard logical flow for this operation involves two distinct clauses:

    1. ORDER BY: Sorts the rows in descending order (DESC) so the newest records appear first. Limiting Clause: Restricts the output to the first 10 rows of that sorted result.

Without the ORDER BY clause, the database engine returns rows in an arbitrary physical storage order, which leads to inconsistent and unreliable results Practical, not theoretical..

Syntax Variations Across Popular Database Systems

While the ANSI SQL standard exists, most major vendors have implemented their own syntax for limiting results. Below are the specific implementations for the most widely used systems.

MySQL and PostgreSQL: The LIMIT Clause

Both MySQL and PostgreSQL share the intuitive LIMIT syntax, making it the most recognizable pattern for developers Easy to understand, harder to ignore. Which is the point..

SELECT * 
FROM your_table_name
ORDER BY id DESC
LIMIT 10;

In this example, id represents the sequencing column. But using DESC ensures the highest IDs (the most recent) are at the top. LIMIT 10 then chops off everything after the tenth row Small thing, real impact..

PostgreSQL Specifics: PostgreSQL also supports the ANSI SQL standard FETCH FIRST syntax (detailed below), but LIMIT remains the de facto standard for simple pagination tasks in the Postgres community Easy to understand, harder to ignore..

Microsoft SQL Server (T-SQL): The TOP Keyword

SQL Server uses the TOP keyword immediately following the SELECT statement. This is a proprietary extension but highly optimized for the engine.

SELECT TOP 10 * 
FROM your_table_name
ORDER BY created_at DESC;

Note that TOP requires parentheses in newer versions when used with variables or expressions (e.g., TOP (10)), though TOP 10 remains valid for static integers Most people skip this — try not to..

Oracle Database: FETCH FIRST and ROWNUM

Modern Oracle versions (12c and later) adopted the ANSI SQL standard OFFSET ... FETCH syntax, which is powerful and readable The details matter here. Simple as that..

SELECT * 
FROM your_table_name
ORDER BY transaction_date DESC
FETCH FIRST 10 ROWS ONLY;

For legacy Oracle versions (11g and earlier), you must use a subquery with the ROWNUM pseudocolumn. This is less intuitive because ROWNUM is assigned before the ORDER BY executes in a single-level query, necessitating a nested approach:

SELECT * 
FROM (
    SELECT * 
    FROM your_table_name
    ORDER BY transaction_date DESC
)
WHERE ROWNUM <= 10;

SQLite: Identical to MySQL/PostgreSQL

SQLite uses the exact same LIMIT syntax as MySQL and PostgreSQL, making it extremely portable for mobile and embedded applications No workaround needed..

SELECT * 
FROM events
ORDER BY timestamp DESC
LIMIT 10;

ANSI SQL Standard: OFFSET ... FETCH

For maximum portability across compliant databases (including PostgreSQL, Oracle 12c+, SQL Server 2012+, and Db2), the standard syntax is:

SELECT * 
FROM your_table_name
ORDER BY id DESC
OFFSET 0 ROWS FETCH NEXT 10 ROWS ONLY;

While verbose, this syntax is explicit about skipping zero rows (OFFSET 0) and fetching the subsequent ten And that's really what it comes down to..

Critical Performance Considerations

Writing a query that returns the correct data is only half the battle; writing one that performs well at scale is the other half. A SELECT * with an ORDER BY on a large table without proper indexing can trigger a full table scan and a costly filesort operation.

The Importance of Indexing

To optimize a SQL query to select last 10 records, you must create an index on the column used in the ORDER BY clause.

  • Single Column Index: If you always sort by created_at, create an index: CREATE INDEX idx_created_at ON your_table(created_at);
  • Descending Index: Some engines (like PostgreSQL and MySQL 8.0+) support explicitly descending indexes (CREATE INDEX idx_created_at_desc ON your_table(created_at DESC);). This can marginally improve performance for ORDER BY ... DESC queries because the engine doesn't need to traverse the index backward.
  • Composite Indexes: If you filter and sort (e.g., WHERE user_id = 5 ORDER BY created_at DESC), a composite index on (user_id, created_at) allows the engine to seek directly to the relevant user and read the index in order, avoiding a sort entirely.

Avoiding SELECT * in Production

While SELECT * is convenient for ad-hoc analysis, it is an anti-pattern in production code.

  1. On top of that, I/O Overhead: Fetching all columns (including large TEXT, BLOB, or JSON fields) increases disk I/O and network latency. 2. Covering Indexes: If you only select specific columns (e.In practice, g. Worth adding: , id, title, created_at), you can create a covering index that includes those columns. The query can be satisfied entirely from the index without ever touching the main table heap (Clustered Index in SQL Server, Heap/Primary Key in InnoDB).

Pagination vs. "Last N Records"

There is a subtle but vital distinction between "get the last 10 records" and "get page 5 of a paginated list.LIMIT 10 is perfect here. That said, "

  • Last N Records: Usually implies a fixed, small window (e. g.Worth adding: , a "Recent Activity" widget). Day to day, * Deep Pagination: Using OFFSET 100000 LIMIT 10 is notoriously slow because the database must scan and discard 100,000 rows. For deep pagination, keyset pagination (also called "seek method") is superior: WHERE id < last_seen_id ORDER BY id DESC LIMIT 10.

And yeah — that's actually more nuanced than it sounds.

Common Pitfalls and How to Avoid Them

Even experienced developers fall into traps when retrieving the latest records. Here are the most frequent mistakes.

1. Relying on Implicit Order

Mistake: SELECT * FROM logs LIMIT 10; (No ORDER BY). Result: Returns 10 arbitrary rows. In MyISAM or heap tables, this might look like insertion order, but in InnoDB (clustered by PK) or after deletes/updates, the physical order changes. Fix: Always use ORDER BY.

2. Sorting by a Non-Unique Column

Mistake: ORDER BY created_at DESC LIMIT 10 where multiple rows share the exact same timestamp

...guarantee deterministic results. Without a secondary sort key, the database may return rows in an arbitrary order when timestamps tie, which can lead to inconsistent results across runs or across different database engines. Always append the primary key (or another unique column) to your ordering clause: ORDER BY created_at DESC, id DESC LIMIT 10

This simple habit eliminates ambiguity and ensures that "the last 10 records" means exactly what you intend, every time.

Conclusion Working with ORDER BY and pagination is where performance meets precision. The right index—single, descending, or composite—turns a potentially expensive sort into a trivial index scan. Being explicit about sort order, especially with non-unique columns, prevents subtle bugs and unstable results. And choosing keyset pagination over OFFSET keeps your queries fast as tables scale. By combining these indexing strategies with mindful column selection and consistent ordering, you build database interactions

...that are fast, predictable, and correct at any scale.

A few principles tie everything together. Second, let the index do the work—design indexes around your actual access patterns rather than adding them speculatively. First, always be explicit: name your columns, state your ORDER BY, and never trust the database to guess your intent. Third, match the technique to the use case: LIMIT for a fixed recent window, keyset pagination for deep pages, and covering indexes when you only need a handful of columns Nothing fancy..

None of these choices are dramatic on their own. A missing secondary sort key or an unnecessary SELECT * rarely breaks anything in development. But under real load—millions of rows, concurrent users, growing tables—these small decisions compound. The query that returned in two milliseconds on a laptop becomes a full table scan that stalls production. Treating ordering and pagination as deliberate design decisions, rather than afterthoughts, is what separates a query that merely works from one that scales.

So the next time you reach for "the latest records," pause on the details: the index that backs the sort, the tie-breaker that guarantees determinism, and the pagination strategy that won't collapse as your data grows. Get those right, and retrieving the last N rows stays simple, fast, and reliable—no matter how large your tables become Not complicated — just consistent. Worth knowing..

New Releases

Just Came Out

More Along These Lines

Adjacent Reads

Thank you for reading about Sql Query To Select Last 10 Records. We hope the information has been useful. Feel free to contact us if you have any questions. See you next time — don't forget to bookmark!
⌂ Back to Home