views:

6738

answers:

5

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
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
You probably want to add `AND table_schema=DATABASE()` since more than one database can have a table with the same name
Alexandre Jasmin
+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
+1, best solution.
musicfreak
I tried this and it just returns a list of all of the id's.
James Simpson
add LIMIT 1, or it returns COUNT(*) lines;
Leonid Shevtsov
good point. fixed.
Jonathan Fingland
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
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
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
@jonathan, completely forgot, thanks
Evert
actually SELECT MAX(id) FROM table should use less memory
Leonid Shevtsov
A: 

try this

Execute this SQL : SHOW TABLE STATUS LIKE ''

and fetch the value of the field "Auto_increment"

+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