Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I'm writing a query to aggregate some data and in my select statement I want to write this:

select coalesce(nullif(sum(field)), '> 1'), 1) from ...

Which, if NULLIF was capable of it, would give me the sum of field unless it was greater than 1, in which case it would give me 1. Of course, I'm asking the impossible of NULLIF, which is intended to do a basic string comparison only.

The reason I don't want to use a CASE statement is because where I have substituted field is an enormous expression which I would have to write out twice if I were to do:

select case when sum(field) > 1 then 1 else sum(field) from ...

I was hoping postgres has an ace up its sleeve and I wouldn't have to do that. Anyone come across this dilemma before?

share|improve this question

1 Answer 1

up vote 2 down vote accepted

So you want the minimum of the sum and 1? That't the LEAST function:

select LEAST(sum(field), 1) from ...
share|improve this answer
1  
Ha! You, sir, are a gentleman and a scholar. –  John Servinis Jan 30 '14 at 12:15

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.