use SQL instead of ruby code for big queries to improve efficiency