groups_query function in sql_queries refactored