I currently have a database with over 6 million rows and growing. I currently do SELECT COUNT(id) FROM table; in order to display the number to my users, but the database is getting large and I have no need to store all of those rows except to be able to show the number. Is there a way to select the auto_increment value to display so that I can clear out most of the rows in the database? Using LAST_INSERT_ID() doesn't seem to work.
+2
A:
SELECT Auto_increment
FROM information_schema.tables
WHERE table_name='the_table_you_want';
James Skidmore
2009-06-01 04:37:22
This is a terrible solution for large databases. This query alone can take full minutes to complete because it has to search through the entire `information_scheme.tables` table. For webhosts with thousands of clients running databases, that single table becomes quite large.
thinkswan
2010-04-04 23:36:33
You probably want to add `AND table_schema=DATABASE()` since more than one database can have a table with the same name
Alexandre Jasmin
2010-04-23 02:07:39
+5
A:
try using the field name in the function
select LAST_INSERT_ID(field) from table limit 1;
but LAST_INSERT_ID() should have worked
Jonathan Fingland
2009-06-01 04:40:49
A:
Next to the information_schema suggestion, this:
SELECT id FROM table ORDER BY id DESC LIMIT 1
should also be very fast, provided there's an index on the id field (which I believe must be the case with auto_increment)
Evert
2009-06-01 04:41:52
You should also add a LIMIT 1 at the end of that so it doesn't end up retrieving every single id just for that.
musicfreak
2009-06-01 04:43:10
this doesn't necessarily give you the last auto-increment value as you can insert/update specific values in the auto_increment'ed column
Jonathan Fingland
2009-06-01 04:46:56
+1
A:
$result = mysql_query("SHOW TABLE STATUS LIKE 'table_name'");
$row = mysql_fetch_array($result);
$nextId = $row['Auto_increment'];
mysql_free_result($result);
This solution is quick even on databases housing thousands (or millions) of tables, because it does not require querying the incredible large information_schema database.
thinkswan
2010-04-04 23:38:18