Refactored sql query code out of calvad/grid_merge