SQL performance improved. Closes #403

The benefit with this commit is really interesting: from 22 queries it has been reduce to only 2, making it really fast.