Clearly you cannot print any counts until after you have read all the data at least once. As you read the DB, compute the counts and store all data (including counts) in a convenient data structure. Pass that structure to a subroutine which formats and prints it any way you like. Any data structure that saves all the data will 'work', but a well designed structure will greatly reduce the amount of code you must write. You have not told us enough about your data or your print requirements for us to offer much help.