Moved the select query code to a method to join together duplicate code