rewrite sql query function