Modified SQL for the function to get data from consumption.
Added better error handling.