title: MYSQL SELECT MAX(id) + 1 where id < 1000
body: <p>I need to use something like:</p>
  
  <pre><code> INSERT into tablename(id) 
       SELECT max(id) + 1 
       FROM tablename
  </code></pre>
  
  <p>where <code>id</code> is less than 1000 and <code>if max(id) = 1000 insert next id as 1</code>, so that the column fills from 1-1000 and start again.</p>
  
  <p>I can have and autoincrement primary key column.</p>
  
  <p>Any help would be greatly appreciated.</p>
  
  <p>I am not an SQL guru, but with the comments below I have done this in Delphi which is where this SQL will be executed. I would still like to know how to do it all in MYSQL and maybe one of the gurus here can help to round this off.</p>
  
  <p>This is what I did:</p>
  
  <pre><code>procedure TForm11.Button1Click(Sender: TObject);
  var
  lastserial : Integer;
  begin
   with LastRowQuery do
    begin
      sql.Clear;
      sql.Add('SELECT autoid, id FROM inctest ORDER BY autoid DESC LIMIT 1;');
      execute;
    end;
    If  LastRowQueryid.value &lt; 1000 then lastserial:=  LastRowQueryid.value + 1
    else
     lastserial := 1;
     with LastRowQuery do
      begin
       sql.Clear;
       sql.Add('Insert into inctest (id) values(:theserial)');
       ParamByName('theserial').Value := lastserial;
     execute;
   end;
  end;
  </code></pre>