Fixing some sql queries