39

My database is Postgres 8. I need to cast data type to another. That means, one of columns data type is varchar and need to cast it into int with Postgres in a SELECT statement.

Currently, I get the string value and cast it into int in Java.
Is there any way to do it? Sample code would be highly appreciated.

1
  • 9
    Just FYI, saying "PostgreSQL 8" is a bit like saying "Windows 6". Windows XP is 5.1 (or 5.2 for x64), Vista is 6.0 and Windows 7 is 6.1. They're all pretty different! It's the same with PostgreSQL; there's 5 years and a huge technical difference between PostgreSQL 8.0 and 8.4, so please always specify the full version. Commented Dec 3, 2012 at 4:01

1 Answer 1

75
+250
cast(varchar_col AS int)  -- SQL standard

or

varchar_col::int          -- Postgres syntax shorthand

Theses syntax variants are valid (almost) anywhere. The second may require nesting parentheses in special situations:

And the first may be required where only functional notation is allowed by syntax restrictions:

There are two more variants:

int4(varchar_col)         -- only works for some type names
int '123'                 -- must be an untyped, quoted string literal

Note how I wrote int4(varchar_col). That's the internal type name and there is also a function defined for it. Wouldn't work as integer() or int().

Note also that the last form does not work for array types. int[] '{1,2,3}' has to be '{1,2,3}'::int[] or cast('{1,2,3}' AS int[]).

Details in the manual here and here.

To be valid for integer, the string must be comprised of an optional leading sign (+/-) followed by digits only. Leading / trailing white space is ignored.

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

2 Comments

it doesn't work if the column is of character data type
@AbelMelquiadesCallejo: What is "it"? All of the above works for data type character (except where explicitly noted). The string must be a valid integer, of course.

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.