Fix database query (bug from data sorting)