Results 1 to 3 of 3

Thread: last row

  1. #1
    Join Date
    Mar 2007
    Posts
    1

    last row

    I'm trying to get the value of the primary key for the last row in the database.
    The Product_ID field is auto-incremented at every entry and i want to find out what the biggest Product_ID in the table is.

    I'm using this sql code but it doesnt work

    SELECT *
    FROM 'Prods'
    WHERE [ `Product_ID` = last];

    any suggestions?

    thanks

  2. #2
    Join Date
    Mar 2007
    Posts
    1

    get last auto row

    Hi

    you can try mysql_insert_id() function to get last autoincrement field value. or you can also use following query:-

    select max(Product_ID) from table_name


    Dhruv

  3. #3
    Join Date
    Mar 2007
    Posts
    16
    Do NOT use the mysql_insert_id() function as this will cause miscellaneous results. e.g. if the last insert you did was NOT in the table that you are now selecting from you will get the wrong answer. Or, if no insert has been performed by this current connection you will get a zero answer or null or an error i expect.

    The right answer is as follows :

    SELECT *
    FROM 'Prods'
    WHERE Product_ID=(SELECT MAX(Product_ID) FROM Prods);

    I am of course assuming that your product id is an integer type. If it isn't the MAX function will not work as expected.

    Tuning tips : put an index on the Product_ID column . e.g.
    ALTER TABLE <table name> ADD INDEX (Product_ID);

Posting Permissions

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