The issue appears to be with the custom SQL query being used. Can you run the query against your Redshift cluster using any IDE or Redshift query editor and check if the error persists? If so, the query has to be modified.
Please let us know if the query works without any issues in your IDE/query editor.