What and how to use SQL coalesce
Example of coalesce
For example, I have declared successCount as Integer (ref type) that allows null unlike primitive types. I am trying to increment this field in my querydsl update query. In this case, we can use coalesce() to set a default value for that field if it is null (which it would be at the start).
Like this with querydsl
public class MyEntityRepositoryImpl implements MyEntityRepositoryCustom {
@Override
public int updateEntitiesByConditions(String reqUrl, LocalDateTime yesterday, LocalDateTime today, String clientName) {
QMyEntity qMyEntity = QMyEntity.myEntity;
JPAQuery<?> query = new JPAQuery<>(entityManager);
return query.update(qMyEntity)
.set(qMyEntity.successCount,
qMyEntity.statusCode.eq(0).then(
qMyEntity.successCount.coalesce(0).add(1)).otherwise(qMyEntity.successCount))
.set(qMyEntity.failCount,
qMyEntity.statusCode.ne(0).then(
qMyEntity.failCount.coalesce(0).add(1)).otherwise(qMyEntity.failCount))
.where(qMyEntity.reqUrl.eq(reqUrl)
.and(qMyEntity.createdAt.between(yesterday, today))
.and(qMyEntity.clientName.eq(clientName)))
.execute();
}
}
for coalesce, i thought it will default to 0 whenever statusCode is 0 so my successCount will not increment beyond 1 (stay at 0 or 1) but actually coalesce will not default it to 0. So once it has an integer assigned like 1, it will not be defaulted back to 0 through the coalesce method. Coalesce is used to check for both null and non null values.