Moved sql logic from views to controller