Correct sql for first() and last()
Closes #531