Fixing SQL query and decoding of the output