#6257: Refactor SQL code