How do I retrieve the first or last n records from a table in SQL?

Learn SQL with Udemy

For an instructor lead, in-depth look at learning SQL click below.


Structured Query Language (SQL) is one of the most powerful tools for manipulating data in relational databases. In this post, we’ll delve into a commonly asked question – how to retrieve the first or last ‘n’ number of records from a table.

Retrieving the First ‘n’ Records

To retrieve the first ‘n’ records from a table, you can use the TOP clause in SQL. Here is an example:

In this example, replace ‘n’ with the number of records you want to retrieve and ‘MyTable’ with the name of your table. [MyColumn] is the column by which the table should be ordered. This query will give you the top ‘n’ records based on their order in the MyColumn field.

Retrieving the Last ‘n’ Records

Now, if we wanted the last ‘n’ records, we might think to simply adjust this to select the bottom ‘n’ rows. Unfortunately, the TOP clause doesn’t work this way. But fret not, there’s a little trick you can do with the ordering.

Just by adding DESC at the end, the statement tells SQL to order the rows in descending order before selecting the top ‘n’. Thus, you end up with the last ‘n’ rows according to the column’s order.

Wrap-Up

And that’s it! You now know how to retrieve the first and last ‘n’ records from a single table in SQL. Remember, understanding the order of operations is essential when making these types of operations: the ORDER BY clause is executed before the TOP clause. Keep practicing and exploring this functionality with different tables and fields, and soon you’ll be an SQL wizard!

Leave a Comment