So I can either give the database a lot more memory to complete this one query … or I can rewrite the inefficient code.

Rewrote it and saved a boatload of performance.