Page 1 of 1

PHP/MySQL retrieval

Posted: Thu Jul 28, 2005 6:27 pm
by mjseaden
Hi

Can you tell me how I retrieve the last two rows from a database table? Is this possible using a query? Currently I use an overly long-winded PHP method of doing it.

Many thanks

Mark

Posted: Thu Jul 28, 2005 6:30 pm
by timvw
Define "last two rows" of a table. Because rows have no order per definition in a table.

If you select them, you can apply an order on them by using the ORDER clause. Witch the ASC | DESC you can change invert them.

Most DBMS support a method to restrict the number of returned rows in a resultset. For example: MySQL and PostgreSQL have LIMIT, MSSQL has TOP.

Posted: Thu Jul 28, 2005 8:08 pm
by harrisonad
if your table has an auto_increment field, you can retrieve that last two rows by ordering them descendingly and limiting the output to 2

Code: Select all

SELECT * FROM table_name ORDER BY id DESC LIMIT 2