Optimize sql queries + some bug fix