4

This code can be used to select the first ten records from a table in mysql. How can I do the same to display last ten records from a table which has 1000 records. I want to display the name in asc order dont want to change that.

   SELECT name, cost FROM test orderby name asc LIMIT 10 ;
blake305
  • 2,196
  • 3
  • 23
  • 52
Murthy
  • 1,502
  • 11
  • 31
  • 45

4 Answers4

7
SELECT q.name, q.cost
    FROM (SELECT name, cost
              FROM test
              ORDER BY name DESC LIMIT 10) q
    ORDER BY q.name ASC;
Joe Stefanelli
  • 132,803
  • 19
  • 237
  • 235
3

The LIMIT clause can take two parameters, which will provide an offset:

The LIMIT clause can be used to constrain the number of rows returned by the SELECT statement. LIMIT takes one or two numeric arguments, which must both be nonnegative integer constants (except when using prepared statements).

With two arguments, the first argument specifies the offset of the first row to return, and the second specifies the maximum number of rows to return. The offset of the initial row is 0 (not 1):

SELECT * FROM tbl LIMIT 5,10; # Retrieve rows 6-15 To retrieve all rows from a certain offset up to the end of the result set, you can use some large number for the second parameter. This statement retrieves all rows from the 96th row to the last:

SELECT * FROM tbl LIMIT 95,18446744073709551615; With one argument, the value specifies the number of rows to return from the beginning of the result set:

SELECT * FROM tbl LIMIT 5; # Retrieve first 5 rows

http://dev.mysql.com/doc/refman/5.0/en/select.html

So with this:

SELECT name, cost FROM test orderby name asc LIMIT 990, 10;
danielrsmith
  • 4,050
  • 3
  • 26
  • 32
2
SELECT name, cost
FROM (SELECT name, cost FROM test orderby name desc LIMIT 10) as test
ORDER BY name asc;
Carson Reinke
  • 713
  • 5
  • 16
0

You can use ROW_NUMBER() clause for this, this will be helpful for you

select top "N" * from (select ROW_NUMBER() OVER(Order by Col_Name desc) as RowNo,* from Table_Name) Table_Name

Jay Ponkia
  • 900
  • 1
  • 8
  • 15