Revert "Revert "clean up and clarify SQL queries""

This reverts commit b94d6534567e852044e909ca6112cf8f3e37b26c.