Backport SQL fix 4a680a9f233bb49422de18cf7751ba6f7ed3d683