# Help Me optimize my query

**URL:** <https://forums.percona.com/t/help-me-optimize-my-query/809>\
**Category:** Other MySQL® Questions\
**Created:** [June 20, 2008, 4:28am UTC](https://forums.percona.com/t/help-me-optimize-my-query/809 "2008-06-20T04:28:44Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![delta2cain1](https://avatars.discourse-cdn.com/v4/letter/d/958977/32.png) [@delta2cain1](https://forums.percona.com/u/delta2cain1)\
**Post date:** [June 20, 2008, 4:28am UTC](https://forums.percona.com/t/help-me-optimize-my-query/809/1 "2008-06-20T04:28:44Z")

</div>

Hi I have a table with 2350k records I have the following query

SELECT Name ,  
count(CASE WHEN P\_A = ‘Y’ and CC = ‘Y’ THEN Name END),  
count(CASE WHEN P\_A = ‘Y’ and CC = ‘Y’ and flag = ‘1’ THEN Name END),  
count(CASE WHEN P\_A = ‘Y’ and CC = ‘Y’ and flag = ‘0’ and Score \>= 76 and Score \< 300 THEN Name END),  
count(CASE WHEN P\_A = ‘Y’ and CC = ‘Y’ and flag = ‘0’ and Score \>= 300 and Score \<= 330 THEN Name END)  
FROM Table1  
WHERE IF($P{StartDate} = $P{EndDate} ,Date\_from\_Table like CONCAT(DATE\_FORMAT(IF(length($P{SelectDate}) \> 4,$P{SelectDate},curdate()), ‘%m%d%Y’),“%”), date\_format(str\_to\_date(CONCAT(SUBSTRING(Date\_from\_Table,1,2 ), “-”,LOWER(SUBSTRING(Date\_from\_Table,4,3)),“-”,‘20’,SUBSTRING(Date\_from\_Table,8,2)), “%d-%b-%Y”), “%Y-%m-%d”) BETWEEN IF(length($P{StartDate}) \> 4,$P{StartDate},curdate()) AND IF(length($P{EndDate}) \> 4,$P{EndDate},curdate()))  
GROUP BY ClientName;

Now The first part of the IF condition works quit fast on its own like .15 sec but when I extend it to consider a range of Date It takes about a minute or so.

Date\_from\_Table unfortunately is in string format and I cannot at the moment alter the Table.

IF(length($P{SelectDate}) \> 4,$P{SelectDate},curdate()) part is for if no date is specified

Also I would like to get the total of the columns . Can I do that??
