Fixed last_entry and first_entry SQL expression that caused some bugs