1

In my select I am using this in order to convert an integer to a money form.

CAST(mytable.discount AS money) AS Discount

But I cannot figure out how to avoid the 'NULL' output if the join fails (for good cause) to bring the optional value.

I've done this to avoid NULLS in the past:

COALESCE(mytable.voucher,'----') AS Voucher

But I cannot figure out how to combined CAST and COALESCE for the same field. I just want my discount NULL fields to be '----'

3
  • 1
    COALESCE(CAST(mytable.discount AS money), '-----') Commented Feb 24, 2015 at 22:26
  • That's tricky, as the "mytable.discount AS money" converts NULLS to $0, which is what it outputs. '-----' never comes to play. Commented Feb 24, 2015 at 22:32
  • "I just want my discount NULL fields to be '----'" - you can't. '---' is a character value, discount is a number. You can't have different datatypes for the same column. You would need to convert all numbers to a string as value (e.g. using to_char()) Commented Feb 24, 2015 at 22:40

1 Answer 1

1

That's tricky, as the "mytable.discount AS money" converts NULLS to $0

It's actually not what happens, but an implicit cast which happens after that.

An expression must have a particular type. In this case it's money. So you see $0.00 as a result of my proposed expression because it's ---- that is converted to money, not NULL.

As a solution you may explicitly convert the inner expression to text like:

SELECT COALESCE(CAST('1' as money)::text, '--');

or

SELECT COALESCE(CAST(null as money)::text, '--');

SQLFiddle demo: http://sqlfiddle.com/#!12/d41d8/2866

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

Comments

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.