ERROR: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'and L.TeamID = T.TeamID and (L.SubDivision = "" or L.SubDivision is null' at line 19 select T.TeamName, T.TeamID, sum(case when R.TeamID is not null then 1 else 0 end) GP, sum(if(Score > OpponentScore, 3, 0)) + sum(if(Score = OpponentScore, 1, 0)) - max(Deduction) P, sum(if(Score > OpponentScore, 1, 0)) W, sum(if(Score < OpponentScore, 1, 0)) L, sum(if(Score = OpponentScore, 1, 0)) D, sum(COALESCE(Score, 0)) GF, sum(COALESCE(OpponentScore, 0)) GA, sum(COALESCE(Score - OpponentScore, 0)) GD, max(Deduction) Deduction, max(DeductionReason) DeductionReason, (select D.EndYear from Divisions D where D.DivisionID = R.DivisionID) EndYear from Teams T, Leagues L left outer join ResultsTemp R on L.DivisionID = R.DivisionID and L.TeamID = R.TeamID where L.DivisionID = and L.TeamID = T.TeamID and (L.SubDivision = "" or L.SubDivision is null) group by L.TeamID order by P desc, Deduction, GA asc, GD desc, T.TeamName