some refactoring and proper sql statements