Refactored API using custom SQL query