SQLite Forum

Help rewriting a query to match the speed of a 2nd query
Login
Greetings!

This query is very slow:

```
SELECT a.ProjID, total(b.AnnualDossier) AS Dossier FROM Project_List AS a 
LEFT JOIN ABT_Budget AS b ON a.ProjID = b.ProjID
AND b.InsertDate = 
(
    SELECT MAX(InsertDate) FROM ABT_Budget WHERE b.ProjID = ProjID
    OR
    b.InsertDate IS Null
)
WHERE a.ProjID IN 
(
           'PR0000014888',
           'PR0000015204',
           'PR0000016639',
           'PR0000016678',
           'PR0000016724'
)
AND a.InsertDate = 
(
    SELECT MAX(InsertDate) FROM Project_List WHERE ProjID = a.ProjID
)
GROUP BY a.ProjID;
PR0000014888|0.0
PR0000015204|0.0
PR0000016639|0.0
PR0000016678|24939.539891
PR0000016724|0.0
Run Time: real 18.511 user 5.859375 sys 12.593750
sqlite>
```

while this one is super fast:

```
SELECT a.ProjID, total(b.AnnualDossier) AS Dossier FROM Project_List AS a 
LEFT JOIN ABT_Budget AS b ON a.ProjID = b.ProjID
AND b.InsertDate = 
(
    SELECT MAX(InsertDate) FROM ABT_Budget  
    WHERE b.ProjID IN 
    (
               'PR0000014888',
               'PR0000015204',
               'PR0000016639',
               'PR0000016678',
               'PR0000016724'
    )
    OR
    b.InsertDate IS Null
)
WHERE a.ProjID IN 
(
           'PR0000014888',
           'PR0000015204',
           'PR0000016639',
           'PR0000016678',
           'PR0000016724'
)
AND a.InsertDate = 
(
    SELECT MAX(InsertDate) FROM Project_List WHERE ProjID = a.ProjID
)
GROUP BY a.ProjID;
PR0000014888|0.0
PR0000015204|0.0
PR0000016639|0.0
PR0000016678|0.0
PR0000016724|0.0
Run Time: real 0.032 user 0.015625 sys 0.000000
```

Programmatically, I can do this easily, but is there a way to rewrite the second without the the duplication of IN groups?  Thanks.

josé