Refactored database query code for commonality