How to increment a field in mysql

Published on September 26th, 2007 by DannyT. Filed under MySQL

Nothing much to see here, just something I’m always forgetting the syntax for as I am often switching between SQL Server, MySQL and Oracle.

I needed to implement an incrementing numeric field for a “reportOrder” field, couldn’t rely on the primary key because I will later be adding the facility to re-order the table based on this field.


SET @pos=0;
INSERT INTO myNewTable(someField, reportOrder)
SELECT fieldName, @pos:=@pos+1
FROM myOldTable
ORDER BY reportOrder;

All i’m doing is assigning the incremented variable value and at the same time reading it in the query. Like I said, nothing major just something I seem to need regularly and couldn’t find a rownum (oracle) equivilent for MySql

2 Responses to “How to increment a field in mysql”

  1. Roger Maynard

    January 23rd, 2008 at 5:29 pm

    Very nice little bit of code…. thanks.

    Having come from Foxpro background, functions like RECNO() are missed.
    Until now that is!

    Brillliant!

    Roger

    Reply
  2. Ben Baker

    June 9th, 2009 at 3:17 pm

    Hey Danny great example.

    I had an issue running a local server (MAMP), where the combined SQL:

    SET @pos=0;
    INSERT INTO myNewTable(someField, reportOrder)
    SELECT fieldName, @pos:=@pos+1
    FROM myOldTable
    ORDER BY reportOrder;

    Did not work in PHP, although it did work in phpMyAdmin…

    Turns out that my PHP could not group queries I think. So I had to do this:

    // set var in sql
    $query = “SET @pos=0″;
    $result = mysql_query($query);
    mysql_free_result($result);

    // now query will run
    $query = “INSERT INTO myNewTable(someField, reportOrder)
    SELECT fieldName, @pos:=@pos+1
    FROM myOldTable
    ORDER BY reportOrder;”

    Thanks again,

    B ;)

    Reply

Leave a Reply

About DannyT

The blog: danny-t.co.uk - General geek talk focusing on Rich Internet Applications, Microsoft and Adobe technologies and the web in general. The business: Moov2.com - RIA development agency Dan Thomas has been an Internet geek since circa 1994. He has been running Moov2 since 2003 and prior to that worked as a Flash developer for one of europes largest E-learning providers.

Copyright © 2010 Danny-T.co.uk

CSS Template By RamblingSoul | WordPress Theme by Theme Lab and Best Hosting.