Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 389
Adrian Fâciu Avatar asked May 28 '10 08:05

Adrian Fâciu


People also ask

How do I select the bottom 10 rows in SQL?

The following is the syntax to get the last 10 records from the table. Here, we have used LIMIT clause. SELECT * FROM ( SELECT * FROM yourTableName ORDER BY id DESC LIMIT 10 )Var1 ORDER BY id ASC; Let us now implement the above query.

How do I select the first and last row in SQL?

To get the first and last record, use UNION. LIMIT is also used to get the number of records you want.


2 Answers

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
like image 92
Ralf de Kleine Avatar answered Sep 21 '22 17:09

Ralf de Kleine


Check the link

SQL SERVER – How to Retrieve TOP and BOTTOM Rows Together using T-SQL

Did you try to using rownumber?

SELECT * 
FROM 
(SELECT *, ROW_NUMBER() OVER (Order BY columnName) as TopFive
   ,ROW_NUMBER() OVER (Order BY columnName Desc) as BottomFive
   FROM Table
)
WHERE TopFive <=5 or BottomFive <=5

http://www.sqlservercurry.com/2009/02/select-top-n-and-bottom-n-rows-using.html

like image 38
hgulyan Avatar answered Sep 19 '22 17:09

hgulyan