Multiple DB fixes

Database fixes from the issue tracker

Need review (sql syntax & fix correctness)

do not merge