How do I select last 5 rows in a table without sorting?

This is just about the most bizarre query I’ve ever written, but I’m pretty sure it gets the “last 5” rows from a table without ordering:

select * 
from issues
where issueid not in (
    select top (
        (select count(*) from issues) - 5
    ) issueid
    from issues
)

Note that this makes use of SQL Server 2005’s ability to pass a value into the “top” clause – it doesn’t work on SQL Server 2000.

Leave a Comment