Start here
The safe first move
Replace .subquery().as_scalar() or .as_scalar() with .scalar_subquery() on the select or query.
Stop before automation when: Complex correlated subqueries tied to broader query redesign. Cases where the subquery shape also needs correction.
Target shape
subq = (
select(func.count(Order.id))
.where(Order.user_id == User.id)
.scalar_subquery()
)