SQLite Forum

ORDER BY not ordering with the correct result
Login
So this is your query (reformatted for eye-bleeding prevention):

```
WITH ProjIDs AS
     (
      VALUES ('PR0000016675'),
             ('PR0000017285'),
             ('PR0000017416'),
             ('PR0000019109'),
             ('PR0000019129'),
             ('PR0000019130'),
             ('PR0000019131'),
             ('PR0000019133'),
             ('PR0000019135'),
             ('PR0000019136'),
             ('PR0000019139'),
             ('PR0000019140'),
             ('PR0000019141'),
             ('PR0000019142'),
             ('PR0000019143'),
             ('PR0000019147'),
             ('PR0000019148'),
             ('PR0000019150'),
             ('PR0000019152'),
             ('PR0000019164'),
             ('PR0000019176'),
             ('PR0000019180'),
             ('PR0000019186'),
             ('PR0000019191'),
             ('PR0000019764')
     )
   SELECT a.*,
          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 ProjIDs
                              OR b.InsertDate IS NULL
                         )
    WHERE a.ProjID IN ProjIDs
      AND a.InsertDate = (
                          SELECT MAX(InsertDate)
                            FROM Project_List
                           WHERE ProjID = a.ProjID
                         )
  GROUP BY a.ProjID
  ORDER BY a.Project_Manager
;
```

I don't see a problem except for this strange construction that I cannot decode:

```
      AND b.InsertDate = (
                          SELECT MAX(InsertDate)
                            FROM ABT_Budget
                           WHERE b.ProjID IN ProjIDs
                              OR b.InsertDate IS NULL
                         )
```

which means that the descent row is chosen if the insertdate is the max(insertdate) of all the projects being reported (theoretically and convolutedly).  In particular this:

b.InsertDate = (b.InsertDate is NULL)

which will *ALWAYS* without exception evaluate to FALSE, so serves no purpose.


What is the "intention" of this code as it seems somewhat confusing?  

We already know that b.ProjID must be in ProjIDs (it is a selection candidate for the table a (Project_List)).  If you simply want the max(InsertDate) for all ProjIDs in ABT_Budget, there is no reason for this to be a correlated query.  You only need to execute it once because the result will not change.  Get rid of the OR and get rid of the b.ProjID (it should just be ProjID).  

Of course, if what you mean is that you want b.InsertDate to be the max(InsertDate) for that project (as in correlated) then it should be b.InsertDate = (select max(insertdate) from abt_budget where ProjId = b.ProjID).