Raw SQL hackery, because filtering in Python is really slow