Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select Top and Last rows in a table (SQL server)

I'm using this statement in SQLServer and it works fine:

SELECT TOP 1000 *       FROM [SomeTable] 

It gives me the TOP 1000 records from SomeTable, now which keyword should I use instead of Top if I need the Bottom 1000 records from the table?

like image 257
Carlos H Avatar asked Mar 28 '12 17:03

Carlos H


People also ask

How do you select top and bottom rows in SQL?

You need to wrap the SELECT and FROM in a derived table and pull the WHERE to the outer query for this to work, like @Paul did in the second method in his answer.

How do I select the last 3 rows in SQL Server?

The TOP clause in SQL Server returns the first N number of records or rows from a table. Applying the ORDER BY clause with DESC, will return rows in descending order. Hence, we get the last 3 rows.

How do I get last 10 rows in SQL Server?

SELECT * FROM ( SELECT * FROM yourTableName ORDER BY id DESC LIMIT 10 )Var1 ORDER BY id ASC; Let us now implement the above query. mysql> SELECT * FROM ( -> SELECT * FROM Last10RecordsDemo ORDER BY id DESC LIMIT 10 -> )Var1 -> -> ORDER BY id ASC; The following is the output that displays the last 10 records.

How do I get last 5 rows in SQL?

METHOD 1 : Using LIMIT clause in descending order As we know that LIMIT clause gives the no. of specified rows from specifies row. We will retrieve last 5 rows in descending order using LIMIT and ORDER BY clauses and finally make the resultant rows ascending.


2 Answers

To get the bottom 1000 you will want to order it by a column in descending order, and still take the top 1000.

SELECT TOP 1000 * FROM [SomeTable] ORDER BY MySortColumn DESC 

If you care for it to be in the same order as before you can use a common table expression for that:

;WITH CTE AS (     SELECT TOP 1000 *     FROM [SomeTable]     ORDER BY MySortColumn DESC )  SELECT *  FROM CTE ORDER BY MySortColumn 
like image 89
Khan Avatar answered Oct 06 '22 03:10

Khan


You must sort your data according your needs (es. in reverse order) and use select top query

like image 42
Luca Avatar answered Oct 06 '22 03:10

Luca