refactored table query