[Solved] My innodb table returns 0 for count(*)

EverSQL Database Performance Knowledge Base

My innodb table returns 0 for count(*)

Database type:

I'm doing this query at the mysql command line (not through any kind of code)

select count(*) from books where
publisher_id = 46 AND deleted = 0 AND status_id = 3;

Returns 0 (sometimes), but remove the count, it has many results.

What could be causing this? I'm throwing this query at the command line (not through any kind of programming layer)

Explaining count query gives:

Using intersect(IDX_cms_books_publisher_id,IDX_cms_books_status_id,IDX_cms_books_deleted); Using where; Using index

How to optimize this SQL query?

The following recommendations will help you in your SQL tuning process.
You'll find 3 sections below:

  1. Description of the steps you can take to speed up the query.
  2. The optimal indexes for this query, which you can copy and create in your database.
  3. An automatically re-written query you can copy and execute in your database.
The optimization process and recommendations:
  1. Create Optimal Indexes (modified query below): The recommended indexes are an integral part of this optimization effort and should be created before testing the execution duration of the optimized query.
Optimal indexes for this query:
ALTER TABLE `books` ADD INDEX `books_idx_publisher_deleted_status_id` (`publisher_id`,`deleted`,`status_id`);
The optimized query:
SELECT
        count(*) 
    FROM
        books 
    WHERE
        books.publisher_id = 46 
        AND books.deleted = 0 
        AND books.status_id = 3

Related Articles



* original question posted on StackOverflow here.