0

I have table autos, In table is column id as auto_increment AND indexed as primary key

I want reset id, that is I need that ids will be queue from 1 to 2,3,4,5,...

For reset id, I run this query:

ALTER TABLE autos AUTO_INCREMENT = 1

This means that now, maximal id must be equivalent rows count right?

But this code

    $res = $db->query("SELECT COUNT(*) AS cnt FROM autos")->fetchAll(PDO::FETCH_ASSOC);
    echo "rows count: ".$res[0]['cnt']."<br>";


    $res = $db->query("SELECT MAX(id) AS id FROM autos")->fetchAll(PDO::FETCH_ASSOC);
    echo "max id".$res[0]['id'];

returns

rows count: 376733
max id: 500000

Why max id and rows quantity not matches? where I am wrong?

Oto Shavadze
  • 40,603
  • 55
  • 152
  • 236

2 Answers2

1

I would never update the ID field like that, you will destroy any relationship with other tables (if you have them) and cause a lot of mess. You should make a new field SortOrder or something that is not a primary key, and then update this field to the new row number.

WernerW
  • 792
  • 11
  • 27
-2

COUNT function will return number of rows in your table while MAX function returns MAX value a column has in your table.

For example, if you have only one record in your table with ID value 5000, then count will return 1 while MAX(ID) will return 5000.

While inserting record, if you do not provide value for auto increment column OR provide NULL value, then MySQL will assign the AUTO-INCREMENT count to this auto increment column and increase the pointer.

Amit
  • 1,365
  • 8
  • 15
  • `For example, if you have only one record in your table with ID value 5000` --- But after reseting ID auto_increment, ID value must be 1 and not 5000, right? – Oto Shavadze Apr 03 '13 at 13:50
  • Yes, now another insert will assign ID 1 if it is available, but MAX is an mathematical function which returns MAX value of column whether it is an auto increment column or normal column. – Amit Apr 03 '13 at 13:52