Adrian Faciu Adrian Faciu - 5 months ago 17
SQL Question

Select top and bottom rows

I'm using SQL Server 2005 and I'm trying to achieve something like this:
I want to get the first x rows and the last x rows in the same select statement.

SELECT TOP(5) BOTTOM(5)


Of course
BOTTOM
does not exist, so I need another solution. I believe there is an easy and elegant solution that I'm not getting. Doing the select again with
GROUP BY DESC
is not an option.

Answer

Using a union is the only thing I can think of to accomplish this

select * from (select top(5) * from logins order by USERNAME ASC) a
union
select * from (select top(5) * from logins order by USERNAME DESC) b
Comments