slightly simplified tortured sqlite logic