SitePoint Sponsor

User Tag List

Results 1 to 3 of 3
  1. #1
    Rusted & Weathered HumanClay's Avatar
    Join Date
    Sep 2000
    Location
    Milwaukee, WI
    Posts
    225
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Select Last Entered Item in Database?

    What would my SQL statement look like to select the very last item entered into the database?
    Steve Caponetto - [profile] [e-mail]
    CreedFeed.com - feed your need for Creed!

  2. #2
    ********* Callithumpian silver trophy freakysid's Avatar
    Join Date
    Jun 2000
    Location
    Sydney, Australia
    Posts
    3,798
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Your best bet is to have a column of type timestamp in the database and record the current timestamp with every insert.

    Then I think this SQL would work:

    SELECT *
    FROM tableName
    WHERE dataAdded = MAX(dateAdded)

    otherwise if that didn't work you could use

    SELECT * FROM tableName
    GROUP BY dateAdded
    HAVING dateAdded = MAX(dateAdded)

  3. #3
    Database Jedi MattR's Avatar
    Join Date
    Jan 2001
    Location
    buried in the database shell (Washington, DC)
    Posts
    1,107
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    In order to get rid of the HAVING clause (which generally hurts performance in mySQL) try:
    Code:
    SELECT *
      FROM tableName
    ORDER BY dateAdded DESC
    LIMIT 1
    This is mostly non-standard (e.g. MySQL specific) but would translate easily to other DBMS'.

    If you wanted to do it the 'SQL' way I'd suggest:
    Code:
    SELECT *
    FROM tableName
    WHERE dateAdded = ( SELECT max( dateAdded )
                          FROM tableName )


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •