More SQL stuff, better code