Invalid SQL: SELECT pr.*, im.image_name_thumb, ct.category_name FROM lac_products_headers as pr LEFT JOIN lac_images as im ON im.parent_id = pr.product_ID AND im.sort_order IN (SELECT MIN(img.sort_order) FROM lac_images as img WHERE img.parent_id = pr.product_ID) LEFT JOIN lac_categories as ct ON ct.category_ID = pr.category WHERE ct.category_ID = ORDER BY case when IfNull(pr.sort_order,0)=0 then 1000000 else pr.sort_order end, pr.item 1064 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 'ORDER BY case when IfNull(pr.sort_order,0)=0 then 1000000 else pr.sort_order end' at line 1.