sql functions tidied up a bit