Removed redundant db query, cleaned up SQL