Moved SQL logic to controller