afanasy: sql code refactoring