Simplify SQL logic, thanks to Skizzerz and Jack