fixed sql query for previous images