Question

does anybody have any suggestions to optimize this query :

SELECT COUNT(client_id) FROM (
  SELECT client_id FROM `cdr` WHERE 
    (DATE(start) BETWEEN '2014-04-21' AND '2014-04-25') AND 
    `service` = 'test' 
    GROUP BY client_id  
    HAVING SUM(duration) > 300 
)as t1

The problem is , inner query scans millions of rows and returns thousands of rows and it makes main query lazy.

Thanks.

Was it helpful?

Solution

Try below query, avoid functions in searching as it does not use index and kill the performance. "start" columns must be indexed.

SELECT COUNT(client_id) FROM (
  SELECT client_id FROM `cdr` WHERE 
    (start BETWEEN '2014-04-21 00:00:00' AND '2014-04-25 23:59:59') AND 
    `service` = 'test' 
    GROUP BY client_id  
    HAVING SUM(duration) > 300 
)as t1

OTHER TIPS

Why not this?I have read somewhere that comparing dates directly with < or > works faster than Between.

SELECT Count(client_id) FROM `cdr` 
WHERE DATE(start) >=  '2014-04-21' 
    AND DATE(start) <= '2014-04-25'
    AND  `service` = 'test' 
GROUP BY client_id  
HAVING SUM(duration) > 300 

What was logic behind having sub query in your sql?

you can use direct query instead of sub query like as

SELECT COUNT(client_id) FROM `cdr` 
WHERE (DATE(start) BETWEEN '2014-04-21' AND '2014-04-25') 
    AND `service` = 'test' 
GROUP BY client_id  
HAVING SUM(duration) > 300 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top