Construction of sql query