1

Duration column in the table is given with 'varchar' data type. It contains decimal values. So I am trying to cast varchar to float/numeric/decimal/double/double precision. But none of those works. why is it not working?

select runner_id, sum(case when cast(duration as decimal) <> '' then 1 else 0 end) as delivered, count(order_id) as total_orders
from t_runner_orders group by runner_id

3
  • And why do you need to cast it to decimal if all you do is check if it is not empty!? Commented Aug 23, 2021 at 17:27
  • And what exactly do you mean with 'But none of those works'. Are there any errors!? If so, then what kind of errors? Commented Aug 23, 2021 at 17:34
  • No checking null is one kind. Further down my case I need to do calcualtion with duration column. I am getting a error: Invalid input syntax for type numeric. Commented Aug 23, 2021 at 20:36

3 Answers 3

1

You can translate '' to null using NULLIF in the cast.

cast(nullif(duration,'') as decimal) is not null

However this will not solve you basic problem which is "varchar' data type. It contains decimal values" NO it does not it contains a string which you hope are decimal values, but nothing prohibits putting 'zero.zero' into it - distinctly not a decimal value. I will go @AdrianKlaver one step further.
3. The only long term solution change the column type to numeric.

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

Comments

0

The reason it's not working is because your duration column contains values which cannot be cast to a numeric type. The specific value throwing the error is an empty string. Also, you shouldn't be comparing a numeric type to an empty string.

Also, if you're comparing a varchar column to a character value in your CASE statement, why are you trying to cast it to a numeric type at all?

For what you're doing here, I would just write it as CASE WHEN duration <> '' THEN 1 ELSE 0 END

And if you do need to cast it to a numeric type at some point, the way to do that would be something like CASE WHEN duration = '' THEN NULL ELSE cast(duration AS DECIMAL) END (asuming that empty strings are the only values in your column which cannot be cast to decimal)

Comments

-1

The problem is you are doing the CAST before the <> ''. The cast fails as there are empty strings in the field. You have several choices:

  1. Use NULL instead of '' in field.

  2. Do duration <> ''

  3. Last and probably the best long term solution change the column type to numeric.

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.