Invalid query: 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 docn IS NOT NULL AND docw = 'S' and docp = 'ÍMG' ORDER BY docm, substr(doc' at line 13 - SELECT DISTINCT docn,DOCM,docp, docv, doci, docd, doca, doco FROM AESSICH_SUB_DOC WHERE mainreference = AND docn IS NOT NULL AND docw = 'S' and docp = 'ÍMG' ORDER BY docm, substr(docd, 7, 4), substr(docd, 4, 2), substr(docd, 1, 2), doco