SQL query improvements, various fixes thanks to pycharm inspector