Significantly more efficient SQL selects.

Fixes #315