Add some SQL functions, refine the code