Fixes bad logic with crazy raw SQL

Thanks to @SmileyChris, @nicolaslara, and @yml for the help!