Refactor, change sql queries to get faster queries