Fix upgrade bug in sql query