On-the-fly refactoring of some queries moved to a function

Signed-off-by: emanuele <emanuele45@gmail.com>