A 'query' is not true or false; it returns results (or no results). But you can do your open
and initial print's in the first iteration of your while loop. That way if there are no results, you don't print anything. After the loop, you can print any final line(s) and close the pipe if there were any results.