3

I am performing a SQL query in Postgres, which selects a numeric field. I need to display a string value as the result of this SELECT, so I am using a CASE statement like this:

Select 
case numeric_field
when 100 then 'some string'
when 200 then 'some other string'

The problem is that if the numeric field has any other value (like 300 for example), I need to display this value (as a string of course). I try to put a CONVERT on the else like this

...
else CONVERT(varchar(10),numeric_field)

But it didn't work. How do I do this?

1
  • 1
    CONVERT is, so far as I'm aware, only in the T-SQL dialect of SQL (found in MS SQL Server and Sybase) Commented Mar 1, 2013 at 14:24

1 Answer 1

6
SELECT CASE numeric_field
          WHEN 100 THEN 'some string'
          WHEN 200 THEN 'some other string'
          ELSE numeric_field::text
       END AS result
       ...

Your statement was incomplete, END was missing. Read the manual here.

To output a numeric field as text, just cast it to text: numeric_field::text, which is the Postgres specific short form of the SQL standard call:

    cast (numeric_field AS text)

See:

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot, i didnt put the end for saving space :P, but your solution works really well, thanks again.

Your Answer

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.