0

how to write a case expression with Postgres? I have this

case
 when rc.stat = 0 Then unpaid
 when rc.stat = 1 Then paid
 when rc.stat = 2 Then dispute
 else rc.stat
end

but when I go to run the statement I get an error of

Error: column "unpaid" does not exist

I have also tried double quotes and brackets around the text values, but all of those options give me errors. Just to note, the values unpaid, paid, dispute are NOT fields in the database, but text values I want to write.

asked Jun 8, 2020 at 13:20

1 Answer 1

0

You need a string constant there, e.g. 'unpaid'.

Because all branches of a CASE expression must return the same data type, you will also need to cast the stat column to text as well (assuming it's some kind of number as you compare it to one)

case
 when rc.stat = 0 Then 'unpaid'
 when rc.stat = 1 Then 'paid'
 when rc.stat = 2 Then 'dispute'
 else rc.stat::text
end

As you only use = as the comparison operator, you can simplify that expression to:

case rc.stat
 when 0 Then 'unpaid'
 when 1 Then 'paid'
 when 2 Then 'dispute'
 else rc.stat::text
end
answered Jun 8, 2020 at 13:23
2
  • Ohhh, so the issue was I was trying to write text values to an int field - but casting the field to a text field resolves :) Commented Jun 8, 2020 at 13:24
  • @TimmyTurner: your original issue was that you didn't write your string constants with single quotes. Commented Jun 8, 2020 at 13:25

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.