1

I would like to return all rows where the sv column, a varchar, is greater than 40. How can I convert sv to an integer on the fly. The line below returns ERROR: invalid input syntax for integer: "SV"

SELECT namefirst, namelast, yearid FROM pitching JOIN people ON pitching.playerID = people.playerID WHERE CAST(sv AS INTEGER)>40;
2
  • 1
    Why are you storing a number as a string? Can you provide sample values? Commented Aug 9, 2021 at 19:49
  • I just copied from an existing csv. Commented Aug 9, 2021 at 20:18

1 Answer 1

2

Postgres doesn't have a built-in way to avoid conversion errors. One method is to use a case expression:

WHERE (CASE WHEN sv ~ '^[0-9]+$' THEN sv::integer END) > 40

Or, if the integers are zero padded on the left, then you might be able to use string comparisons:

WHERE sv >= '40'

However, this runs the risk of matching non-numeric values (which you seem to have given the error you are getting).

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.