Table Count in database - mysql

I want to get table count of my database. I have two queries and both queries giving different result. Can someone please tell me what is difference between these two queries ?
1) SELECT count(*) FROM INFORMATION_SCHEMA.TABLES ;
2) show tables;
I want to get total count of tables of my database. First I execute "Show tables;" and checked how much row it returns. Then I execute "SELECT count(*) FROM INFORMATION_SCHEMA.TABLES ;" but this query giving more count than previous.

SELECT count(*) FROM INFORMATION_SCHEMA.TABLES ;
This query returns all the tables like user-created and system tables of the database.
show tables;
This query returns only user-created tables from the database.
That's why first query returns more than count of second query.

Related

SELECT COUNT(*)... & SELECT table_name,table_rows ...; Giving different results (row count), can anyone please explain, why?

I am transferring tables from 1 database(MySQL) to another database(MYSQL).
To check table data i am counting number of rows in given table(s) but i am getting different row count for same table(s) when I am executing following 2 queries. Can anyone please explain why it is happening? (also i have uploaded screen of query result)
Queries
1.
SELECT COUNT(*) FROM test1; (giving result as 134)
2.
SELECT table_name,table_rows FROM information_schema.tables WHERE table_schema='career';(giving result as 171)**
Nothing to worry about here. The right way to find the number of rows is your first query:
Select count(*) from table;
Count(*) will count all rows even when the whole row is null. That won't be the case though as almost all tables have Primary key and you just added one to your table.
Table_rows will only give rough estimate of the number of rows in your table and that may vary often if you run that query various times.
For more info, Click here
Hope it helps!

Why the difference between record count values

Actual my purpose is to find out the number of records present in my database so in order to find out that i have executed the query like select sum(table_rows) from information_schema.tables where table_schema='database_name';
It gave me some value like 90658965
After that i need number of records present in the individual table so i have executed the following query select table_rows,table_name from information_schema.tables where table_schema='database_name';
I have got result like 3781(table_rows) and tickets(table_name)
So in order to cross verify i have executed the query like
select count(*) from tickets;
I have got result like 3552
why there is a difference between the count of tables for the above two query's
The storage engine for the tickets table is innodb
As documented under The INFORMATION_SCHEMA TABLES Table:
For InnoDB tables, the row count is only a rough estimate used in SQL optimization. (This is also true if the InnoDB table is partitioned.)
SELECT COUNT(*) FROM TABLENAME
this query is a resource incentive operation.
total return by information_schema.tables would be the right one

difference in DataBases

How to make query to information_schema.tables to get list of available tables which is exist in one DB but not exist in another one, something like diff but more suitable. I just need sql query.
So i have Db's like A,B,C,D and all these DB's should has the same tables, how I can check it ?
try
select *
from INFORMATION_SCHEMA.tables
group by table_name
having count(table_schema) < 4
if you have 4 DB's. If more you have to adjust the having clause.
This query give you all unique tables in all databases.
SELECT *,count(TABLE_NAME)
FROM
`TABLES` group by table_name
having count(TABLE_NAME)=1
And if you want repeated table names then use this
SELECT *,count(TABLE_NAME)
FROM
`TABLES` group by table_name
having count(TABLE_NAME)>1

MySQL: Fastest way to count number of rows

Which way to count a number of rows should be faster in MySQL?
This:
SELECT COUNT(*) FROM ... WHERE ...
Or, the alternative:
SELECT 1 FROM ... WHERE ...
// and then count the results with a built-in function, e.g. in PHP mysql_num_rows()
One would think that the first method should be faster, as this is clearly database territory and the database engine should be faster than anybody else when determining things like this internally.
When you COUNT(*) it takes in count column indexes, so it will be the best result. MySQL with MyISAM engine actually stores row count, it doesn't count all rows each time you try to count all rows. (based on primary key's column)
Using PHP to count rows is not very smart, because you have to send data from MySQL to PHP. Why do it when you can achieve the same on the MySQL side?
If the COUNT(*) is slow, you should run EXPLAIN on the query, and check if indexes are really used, and where they should be added.
The following is not the fastest way, but there is a case, where COUNT(*) doesn't really fit - when you start grouping results, you can run into a problem where COUNT doesn't really count all rows.
The solution is SQL_CALC_FOUND_ROWS. This is usually used when you are selecting rows but still need to know the total row count (for example, for paging).
When you select data rows, just append the SQL_CALC_FOUND_ROWS keyword after SELECT:
SELECT SQL_CALC_FOUND_ROWS [needed fields or *] FROM table LIMIT 20 OFFSET 0;
After you have selected needed rows, you can get the count with this single query:
SELECT FOUND_ROWS();
FOUND_ROWS() has to be called immediately after the data selecting query.
In conclusion, everything actually comes down to how many entries you have and what is in the WHERE statement. You should really pay attention on how indexes are being used, when there are lots of rows (tens of thousands, millions, and up).
After speaking with my team-mates, Ricardo told us that the faster way is:
show table status like '<TABLE NAME>' \G
But you have to remember that the result may not be exact.
You can use it from command line too:
$ mysqlshow --status <DATABASE> <TABLE NAME>
More information: http://dev.mysql.com/doc/refman/5.7/en/show-table-status.html
And you can find a complete discussion at mysqlperformanceblog
This query (which is similar to what bayuah posted) shows a nice summary of all tables count inside a database:
(simplified version of stored procedure by Ivan Cachicatari which I highly recommend).
SELECT TABLE_NAME AS 'Table Name', TABLE_ROWS AS 'Rows' FROM information_schema.TABLES WHERE TABLES.TABLE_SCHEMA = '`YOURDBNAME`' AND TABLES.TABLE_TYPE = 'BASE TABLE';
Example:
+-----------------+---------+
| Table Name | Rows |
+-----------------+---------+
| some_table | 10278 |
| other_table | 995 |
Great question, great answers. Here's a quick way to echo the results if anyone is reading this page and missing that part:
$counter = mysql_query("SELECT COUNT(*) AS id FROM table");
$num = mysql_fetch_array($counter);
$count = $num["id"];
echo("$count");
I've always understood that the below will give me the fastest response times.
SELECT COUNT(1) FROM ... WHERE ...
If you need to get the count of the entire result set you can take following approach:
SELECT SQL_CALC_FOUND_ROWS * FROM table_name LIMIT 5;
SELECT FOUND_ROWS();
This isn't normally faster than using COUNT albeit one might think the opposite is the case because it's doing the calculation internally and doesn't send the data back to the user thus the performance improvement is suspected.
Doing these two queries is good for pagination for getting totals but not particularly for using WHERE clauses.
Try this:
SELECT
table_rows "Rows Count"
FROM
information_schema.tables
WHERE
table_name="Table_Name"
AND
table_schema="Database_Name";
I did some benchmarks to compare the execution time of COUNT(*) vs COUNT(id) (id is the primary key of the table - indexed).
Number of trials:
10 * 1000 queries
Results:
COUNT(*) is faster 7%
VIEW GRAPH: benchmarkgraph
My advice is to use: SELECT COUNT(*) FROM table
EXPLAIN SELECT id FROM .... did the trick for me. and I could see the number of rows under rows column of the result.
Perhaps you may want to consider doing a SELECT max(Id) - min(Id) + 1. This will only work if your Ids are sequential and rows are not deleted. It is however very fast.
This is the best query able to get the fastest results.
SELECT SQL_CALC_FOUND_ROWS 1 FROM `orders`;
SELECT FOUND_ROWS();
In my benchmark test: 0.448s
This query takes 4.835s
SELECT SQL_CALC_FOUND_ROWS * FROM `orders`;
SELECT FOUND_ROWS();
count * takes 25.675s
SELECT count(*) FROM `orders`;
If you don't need super-exact count, then you can set a lower transaction isolation level for the current session. Do it like this:
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;
SELECT count(*) FROM the_table WHERE ...;
COMMIT; /* close the transaction */
It is also good to have an index that matches the WHERE condition.
It really speeds up the counting for big InnoDB tables. I checked it on a table with ~700M rows and heavy load, it works. It reduced the query time from ~451 seconds to ~2 seconds.
I took the idea from this answer: https://stackoverflow.com/a/918092/1743367
A count(*) statement with a where condition on the primary key returned the row count much faster for me avoiding full table scan.
SELECT COUNT(*) FROM ... WHERE <PRIMARY_KEY> IS NOT NULL;
This was much faster for me than
SELECT COUNT(*) FROM ...
I handled tables for the German Government with sometimes 60 million records.
And we needed to know many times the total rows.
So we database programmers decided that in every table is record one always the record in which the total record numbers is stored. We updated this number, depending on INSERT or DELETE rows.
We tried all other ways. This is by far the fastest way.

How to get the total numbers of rows stored in the MySQL database table?

Is there a MySQL command to count the number of rows in a table, and if so, what is it?
MySQL COUNT() function
SELECT COUNT(*) FROM table
A nice way to get AN ESTIMATE of the number of rows can be via meta-data information in the information_schema tables.
Note, this is just an ESTIMATE used for query optimizations.
There may be a way to get exact # of rows from the information_schema, but I am not 100% sure if this is possible.
SELECT table_schema, table_name, table_rows
FROM information_schema.tables
ORDER BY table_rows DESC
This gives you the number of rows from a specific table name that you set:
SELECT TABLE_ROWS from information_schema.TABLES where table_name = "your_specific_table_name_here";