Planning and heuristic optimization of queries