Query fix for compatibility between sqlite and pg