Fixed scoping of select statement