2

I am trying to reset the auto increment value in one of my tables based on the number of rows currently in it. Here is the code I have so far.

SET @numrows = 0; SELECT COUNT(*) total, @numrows := COUNT(*) + 1 numrows FROM maj_user ; ALTER TABLE `maj_user` AUTO_INCREMENT = @numrows ; 

This works great if I execute it in MySQL Workbench. However, I need to save this as an SQL file and execute it as part of a database import script. If I do this, I get this:

ERROR 1064 (42000) at line 39: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '@numrows' at line 1 

Line 39 is the ALTER TABLE statement. Any ideas?

5
  • Shouldn't you be setting the AUTO_INCREMENT value to IFNULL(MAX(id),0)+1 or whatever your auto-incrementing column is? By fluke it might be the same as the number of rows, but this is by no means reliable. Commented Apr 1, 2013 at 19:05
  • Under typical circumstances, yes. In this particular case, the probability of the MAX and COUNT being equal is a certainty. Commented Apr 1, 2013 at 19:07
  • So you never, ever delete rows? How is your AUTO_INCREMENT ending up in the wrong state, then? Commented Apr 1, 2013 at 19:08
  • Earlier parts of this application shave the last x number of records from the end of the table, leaving a special set of records from id #1 up that never get removed. Yes, it does delete, but always the same set. I could use a solution to my question as presented. Let's keep to questions intended to get to one. Commented Apr 1, 2013 at 19:21
  • Just trying to understand your requirements better. Commented Apr 1, 2013 at 19:50

1 Answer 1

0

Can you change your syntax to skip actually setting @numrows? I'm not sure what the problem is but a workaround seems to be something like:

ALTER TABLE `maj_user` AUTO_INCREMENT = (SELECT COUNT(*) + 1 from maj_user); 
Sign up to request clarification or add additional context in comments.

4 Comments

Error Code: 1064. You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '(SELECT COUNT(*) + 1 from maj_user)' at line 1
You should use the primary key instead of * on count statements for performance reasons.
You could probably do this in two queries, one to fetch, one to adjust, if you're not too worried about race conditions where a record might be inserted before you get to twiddling it, or you're prepared to lock the table briefly.
This claims setting it to 0 will actually make it one higher than the largest value in the table. I'd create a test table before doing it to your actual table as I cannot verify: stackoverflow.com/questions/3595584/…

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.