Page 1 of 1

last data in the database

Posted: Sat Sep 01, 2007 1:46 am
by myharshdesigner
how to get last data in the database ?

Posted: Sat Sep 01, 2007 6:43 am
by superdezign
In the whole database? No clue. You mean from a specific table?
You'd use ORDER BY and LIMIT.

i.e.

Code: Select all

select `columnName` from `tableName` order by `id` desc limit 1;

Posted: Sat Sep 01, 2007 6:50 am
by aceconcepts
If you're using MySQL you could use:

assuming you have an auto-increment id field

Code: Select all

SELECT *
FROM tbl
ORDER BY fieldId DESC
LIMIT 1
or

Code: Select all

SELECT max(id) as lastrow FROM tbl
Depending on the version of MySQL you are using you can use MAX() or GREATEST.

Posted: Sat Sep 01, 2007 11:29 am
by superdezign
aceconcepts wrote:

Code: Select all

SELECT max(id) as lastrow FROM tbl
Depending on the version of MySQL you are using you can use MAX() or GREATEST.
That would give you the latest id.

Posted: Tue Sep 04, 2007 6:17 am
by aceconcepts
yes, the last inserted record.

Posted: Tue Sep 04, 2007 6:25 am
by CoderGoblin
If you are not using MySQL (generally assumed you are if you do not mention any other) you may have to do something different. For Postgres you generally have to get the ID of what is termed a sequence before you create the table row (setting the table row id to the previously retrieved value). Whilst this may seem a pain, it is easy to do and has the advantage you can use the same sequence on multiple tables.