Explain Codes LogoExplain Codes Logo

Sql Server SELECT LAST N Rows

sql
performance
best-practices
join
Nikita BarsukovbyNikita Barsukov·Nov 4, 2024
TLDR

Get your latest N rows easily in SQL! Just use TOP combined with ORDER BY on a key field (like id or date) and sort it in descending order. This will effectively flip your dataset to bring the latest entries to the top. Let's say you want the 5 most recent entries:

SELECT TOP 5 * FROM TableName ORDER BY KeyColumn DESC;

Substitute TableName with your table name and KeyColumn with your sort column e.g. id, or timestamp.

Query strategies for larger datasets

If you're dealing with massive datasets, using ORDER BY may not be a practical solution due to its demanding performance. Here are a few alternative strategies you might consider:

1. "ROW_NUMBER()": Targeted selection

Utilize the ROW_NUMBER() function with Common Table Expressions (CTE) or a subquery to elegantly navigate huge datasets. It assigns a unique row number to each row, providing an easy way to target specific rows.

-- It's like assigning unique roll numbers to students! WITH NumericalTable AS ( SELECT *, ROW_NUMBER() OVER (ORDER BY KeyColumn DESC) AS rownum FROM TableName ) SELECT * FROM NumericalTable WHERE rownum <= N;

Remember to replace N with your desired number of rows.

2. "EXCEPT": Mathematical alternative

The EXCEPT operator provides another potent method to select the last N rows. It excludes all rows except the last N by performing a set difference operation.

-- Math, who knew you'd come in handy in programming! SELECT * FROM TableName EXCEPT SELECT TOP (SELECT COUNT(*) - N FROM TableName) * FROM TableName;

Handy when you want to avoid lengthy execution times of full sort operations on large tables, eh?

3. "OFFSET FETCH" on SQL Server 2012+

SQL Server 2012 introduced OFFSET FETCH, a neat trick for paging through results. It allows you to skip past rows and only return a fixed number of rows from a specific point.

-- It's like flipping through pages of a book! SELECT * FROM TableName ORDER BY KeyColumn DESC OFFSET (SELECT COUNT(*) - N FROM TableName) ROWS FETCH NEXT N ROWS ONLY;

Mind the performance!

When selecting the last N rows, it's critical to keep an eye on the execution time, particularly with large datasets. Indexes on your sort column can dramatically simplify your life by boosting query performance.

Visualization

Think of your data as a train ride (🚂), each cart representing a single row in your SQL Server data:

Data Train (🚂): [Car 1 - Oldest 📆, ..., Car N-2 🚃, Car N-1 🚃, Car N - Newest 🆕]

When we perform a SELECT LAST N Rows, it's like we're catching the last few train cars:

👀: [Car N-1 🚃, Car N - Newest 🆕]

The SQL that drives this is:

SELECT * FROM (SELECT TOP N * FROM YourTable ORDER BY YourColumn DESC) sub ORDER BY YourColumn ASC

Keeping up with the end of your data train ensures you won't miss any new arrivals! 🚃🔄🚃