[Solved] CASE query optimization

EverSQL Database Performance Knowledge Base

CASE query optimization

SELECT
  COUNT(CASE WHEN VALUE = 1 THEN 1 END) AS score_1,
  COUNT(CASE WHEN VALUE = 2 THEN 1 END) AS score_2,
  COUNT(CASE WHEN VALUE = 3 THEN 1 END) AS score_3,
  COUNT(CASE WHEN VALUE = 4 THEN 1 END) AS score_4,
  COUNT(CASE WHEN VALUE = 5 THEN 1 END) AS score_5,
  COUNT(CASE WHEN VALUE = 6 THEN 1 END) AS score_6,
  COUNT(CASE WHEN VALUE = 7 THEN 1 END) AS score_7,
  COUNT(CASE WHEN VALUE = 8 THEN 1 END) AS score_8,
  COUNT(CASE WHEN VALUE = 9 THEN 1 END) AS score_9,
  COUNT(CASE WHEN VALUE = 10 THEN 1 END) AS score_10
FROM
  `answers`
WHERE
`created_at` BETWEEN '2017-01-01 00:00:00' AND '2019-11-30 23:59:59' 

Is there a way to optimize this query, because I have 4 million answer records in my DB, and it runs very slowly?

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 `answers` ADD INDEX `answers_idx_created_at` (`created_at`);
The optimized query:
SELECT
        COUNT(CASE 
            WHEN `answers`.VALUE = 1 THEN 1 END) AS score_1,
COUNT(CASE 
    WHEN `answers`.VALUE = 2 THEN 1 END) AS score_2,
COUNT(CASE 
    WHEN `answers`.VALUE = 3 THEN 1 END) AS score_3,
COUNT(CASE 
    WHEN `answers`.VALUE = 4 THEN 1 END) AS score_4,
COUNT(CASE 
    WHEN `answers`.VALUE = 5 THEN 1 END) AS score_5,
COUNT(CASE 
    WHEN `answers`.VALUE = 6 THEN 1 END) AS score_6,
COUNT(CASE 
    WHEN `answers`.VALUE = 7 THEN 1 END) AS score_7,
COUNT(CASE 
    WHEN `answers`.VALUE = 8 THEN 1 END) AS score_8,
COUNT(CASE 
    WHEN `answers`.VALUE = 9 THEN 1 END) AS score_9,
COUNT(CASE 
    WHEN `answers`.VALUE = 10 THEN 1 END) AS score_10 
FROM
`answers` 
WHERE
`answers`.`created_at` BETWEEN '2017-01-01 00:00:00' AND '2019-11-30 23:59:59'

Related Articles



* original question posted on StackOverflow here.