views:

188

answers:

3

I want to know that my sql execute count queries in linear time or in log(n) time i think that if query parameter was indexed it can do it by cubing

+1  A: 

It all depends on the query, or more precisely, on the query plan MySql eventually select to process the query.

Also it all depend what we mean by 'n', in these big O expression. For example if 'n' is the count value eventually returned, and if that counts is that produced by a query which requires iteratively scanning multiple tables, the complexity could be worse than linear.

mjv
+1  A: 

The answer to this is complicated. Not only does it depend on the number of tables involved, but it can also depend on what storage engine you're using.

Having said that, this is what the manual says:

COUNT(*) is optimized to return very quickly if the SELECT retrieves from one table, no other columns are retrieved, and there is no WHERE clause. For example:

mysql> SELECT COUNT(*) FROM student;

This optimization applies only to MyISAM tables only, because an exact row count is stored for this storage engine and can be accessed very quickly. For transactional storage engines such as InnoDB, storing an exact row count is more problematic because multiple transactions may be occurring, each of which may affect the count.

-- MySQL Manual

R. Bemrose
My query contains where clause but the attribute in where clause has indexed. Can I using for example cubing or the same technics?
tavallaie
+1  A: 
  • MyISAM will return immediatelly.
  • InnoDB will do PK scan, so time will lineary increase with number of records.

If you need to see approximately how many records InnoDB table holds, the fastest way is using

EXPLAIN select * from student;

(but innodb statistics may be wrong, so 40% error is quite possible also)

noonex
This is true of plain "SELECT COUNT(*) FROM myTable" queries. The time complexity however varies, with queries that include any filter or other constraints.
mjv
40% error? How could it be so far wrong? This is a real question, I'm not a MySQL user so I don't know.
Jeff Davis
40% error in predicted number of rows to be scanned is very possible for InnoDB. But execution plan in 97% is accurate. (well, it may hurt in other 3% when index hint is needed)
noonex