Changed max query to work with postgresql (really!)