last data in the database

Questions about the MySQL, PostgreSQL, and most other databases, as well as using it with PHP can be asked here.

Moderator: General Moderators

Post Reply
myharshdesigner
Forum Commoner
Posts: 43
Joined: Sat Apr 21, 2007 8:23 pm

last data in the database

Post by myharshdesigner »

how to get last data in the database ?
User avatar
superdezign
DevNet Master
Posts: 4135
Joined: Sat Jan 20, 2007 11:06 pm

Post 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;
User avatar
aceconcepts
DevNet Resident
Posts: 1424
Joined: Mon Feb 06, 2006 11:26 am
Location: London

Post 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.
User avatar
superdezign
DevNet Master
Posts: 4135
Joined: Sat Jan 20, 2007 11:06 pm

Post 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.
User avatar
aceconcepts
DevNet Resident
Posts: 1424
Joined: Mon Feb 06, 2006 11:26 am
Location: London

Post by aceconcepts »

yes, the last inserted record.
User avatar
CoderGoblin
DevNet Resident
Posts: 1425
Joined: Tue Mar 16, 2004 10:03 am
Location: Aachen, Germany

Post 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.
Post Reply