Improved sql queries.

see #392
Previous fix was too heavy :p

see #399