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.

- 7,738
- 2
- 38
- 67

- 13,488
- 26
- 83
- 108
-
3Have you tried other solutions, James? They seem to be better... – Dan Sep 01 '11 at 07:06
-
If you have never deleted a record, then the auto_increment would be correct, but otherwise it's off by the number of records deleted since the birth of the table. – Reactgular Dec 19 '12 at 17:48
-
2Just to be clear about the difference, getting the number of rows tells you how many rows are there now. If you want your count to include rows that were once there but then deleted, you do need auto_increment (though this will also include rows that were only present within a transaction that was rolled back rather than committed). – octern Jan 09 '13 at 20:47
-
1Or if someone hardcoded a value that was higher then the current auto_increment for some insert, you'd skip some too. I'd say that auto_increment is not a real trustworthy way to count. – Nanne Jan 11 '13 at 09:17
12 Answers
Following is the most performant way to find the next AUTO_INCREMENT
value for a table. This is quick even on databases housing millions of tables, because it does not require querying the potentially large information_schema
database.
mysql> SHOW TABLE STATUS LIKE 'table_name';
// Look for the Auto_increment column
However, if you must retrieve this value in a query, then to the information_schema
database you must go.
SELECT `AUTO_INCREMENT`
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = 'DatabaseName'
AND TABLE_NAME = 'TableName';

- 4,818
- 2
- 30
- 39
-
-
Not sure. I reckon this way is quicker because it does not require you to select a record, but I haven't run tests to confirm that. Either or should work for most applications. – Graham Swan Sep 01 '11 at 08:02
-
2This works as advertised (as opposed to the LAST_INSERT_ID answer) and is very fast. – Timm Sep 01 '11 at 20:48
-
3This should be selected as the correct answer for this question. This method is far more efficient an does not require digging through information_schema.tables which can be taxing on shared mySQL server. @thinkswan great and simple solution. – Austin S. Jan 25 '12 at 18:27
-
6
-
1This doesn't answer the question; it's not MySQL syntax code. You need a PHP preprocessor, for example you couldn't use this in a DML script. – Mark McKenna Dec 19 '12 at 19:27
-
6Why did you feel the need to mud your answer with PHP code? The question was about SQL. – Francisco Zarabozo Apr 25 '13 at 00:51
If it's only about getting the number of records (rows) I'd suggest using:
SELECT TABLE_ROWS
FROM information_schema.tables
WHERE table_name='the_table_you_want' -- Can end here if only 1 DB
AND table_schema = DATABASE(); -- See comment below if > 1 DB
(at least for MySQL) instead.

- 18,591
- 15
- 71
- 96

- 49,340
- 32
- 108
- 136
-
8This 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. – Graham Swan Apr 04 '10 at 23:36
-
13You probably want to add `AND table_schema=DATABASE()` since more than one database can have a table with the same name – Alex Jasmin Apr 23 '10 at 02:07
-
@thinkswan, I bet by adding the table_schema restriction the performance of this query jumps hugely. – Mark McKenna Dec 19 '12 at 19:29
-
8Does this return the autoincrement_id value or the number of rows in the table? I think this should be `SELECT AUTO_INCREMENT FROM...`. – jjmontes Jan 11 '13 at 14:58
-
8@jjmontes is correct - `TABLE_ROWS` and `AUTO_INCREMENT` are different statistics and the OP question is misleading. `TABLE_ROWS` = rows in a table, `AUTO_INCREMENT` = value of auto inc counter. I can have a table with only one row, but have the AUTO_INCREMENT set to 1,000,000. (This can easily happen if you delete, for example, the first 999,999 rows from a table!). The `AUTO_INCREMENT` value is actually user configurable, so it's very important to never, ever make the assumption that the row count and auto inc are the same thing. `TABLE_ROWS !== AUTO_INCREMENT` – methai Apr 05 '13 at 14:28
-
This query is inaccurate if there are deletion of entries, does it not? – George Jul 24 '13 at 07:56
try this
Execute this SQL:
SHOW TABLE STATUS LIKE '<tablename>'
and fetch the value of the field Auto_increment

- 22,561
- 8
- 51
- 62
I'm not sure why no one has suggested the following. This will get the auto_increment value using just SQL (no need for using PHP's mysql_fetch_array
):
SELECT AUTO_INCREMENT FROM information_schema.tables WHERE TABLE_NAME = 'table'

- 6,293
- 2
- 40
- 68
-
2This is by far the best answer, with one caveat. I've suggested an edit, but for those who see this in the meantime: you should include AND TABLE_SCHEMA='database' as well, for servers containing multiple databases with the same table name. – matt Dec 17 '13 at 17:22
if you directly get get max number by writing select query then there may chance that your query will give wrong value. e.g. if your table has 5 records so your increment id will be 6 and if I delete record no 5 the your table has 4 records with max id is 4 in this case you will get 5 as next increment id. insted to that you can get info from mysql defination itself. by writing following code in php
<?
$tablename = "tablename";
$next_increment = 0;
$qShowStatus = "SHOW TABLE STATUS LIKE '$tablename'";
$qShowStatusResult = mysql_query($qShowStatus) or die ( "Query failed: " . mysql_error() . "<br/>" . $qShowStatus );
$row = mysql_fetch_assoc($qShowStatusResult);
$next_increment = $row['Auto_increment'];
echo "next increment number: [$next_increment]";
?>

- 3,028
- 3
- 25
- 34
SELECT id FROM table ORDER BY id DESC LIMIT 1
can returns max id not auto increment id. both are different in some conditions

- 1,081
- 3
- 12
- 23
If you do not have privilege for "Show Status" then, The best option is to, create two triggers and a new table which keeps the row count of your billion records table.
Example:
TableA >> Billion Records
TableB >> 1 Column and 1 Row
Whenever there is insert query on TableA(InsertTrigger), Increment the row value by 1 TableB
Whenever there is delete query on TableA(DeleteTrigger), Decrement the row value by 1 in TableB

- 11
- 1
$next_id = mysql_fetch_assoc(mysql_query("SELECT MAX(id) FROM table"));
$next_id['MAX(id)']; // next auto incr id
hope it helpful :)

- 61
- 1
- 3
-
this wont work if the previous last record is deleted, this will return the max row id that exists but not the next to be auto incremented id, – mahen3d Aug 11 '13 at 02:04
Controller
SomeNameModel::_getNextID($this->$table)
MODEL
class SomeNameModel extends CI_Model{
private static $db;
function __construct(){
parent::__construct();
self::$db-> &get_instance()->db;
}
function _getNextID($table){
return self::$db->query("SHOW TABLE STATUS LIKE '".$table."' ")->row()->Auto_increment;
}
... other stuff code
}

- 401
- 3
- 9
None of these answers seem to be quite right. I tried them all. Here are my results.
Sending query: SELECT count(*) FROM daximation
91
Sending query: SELECT Auto_increment FROM information_schema.tables WHERE table_name='daximation'
96
Sending query: SHOW TABLE STATUS LIKE 'daximation'
98
Sending query: SELECT id FROM daximation ORDER BY id DESC LIMIT 1
97
here's the screenshot: https://www.screencast.com/t/s8c3trYU
Here is my PHP code:
$query = "SELECT count(*) FROM daximation";
$result = sendquery($query);
$row = mysqli_fetch_row($result);
debugprint( $row[0]);
$query = "SELECT Auto_increment FROM information_schema.tables WHERE table_name='daximation'";
$result = sendquery($query);
$row = mysqli_fetch_row($result);
debugprint( $row[0]);
$query = "SHOW TABLE STATUS LIKE 'daximation'";
$result = sendquery($query);
$row = mysqli_fetch_row($result);
debugprint( $row[10]);
$query = "SELECT id FROM daximation ORDER BY id DESC LIMIT 1";
$result = sendquery($query);
$row = mysqli_fetch_row($result);
debugprint( $row[0]);

- 6,268
- 4
- 55
- 59
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)

- 93,428
- 18
- 118
- 189
-
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. – Sasha Chedygov Jun 01 '09 at 04:43
-
5this 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 Jun 01 '09 at 04:46
-
7
-
4
-
If the highest `id` is deleted, it will show the next one down, not the actual `AUTO_INCREMENT`. – uınbɐɥs Sep 19 '12 at 05:06
-
1this is really only valid if no changes have been made -- i.e. no deletes – fijiaaron Oct 11 '12 at 22:54
-
Neither the auto-increment or this method will tell how many rows are in the table, but this answer is the most logical approach. The exact auto-increment value isn't what the question was asking. It was asking how many rows were the table. I think the COUNT() method is the only way to tell. – Reactgular Dec 19 '12 at 17:56
Couldn't you just create a record in a separate table or whatever with a column called Users and UPDATE it with the last inserted id on User Registration?
Then you would just check this field with a simple query.
It might be rough but it would work perfectly.

- 32,502
- 98
- 258
- 410