Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Postgres data type cast

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.

like image 991
Débora Avatar asked Dec 03 '12 03:12

Débora


People also ask

How do I cast data type in PostgreSQL?

PostgreSQL supports a CAST operator that is used to convert a value of one type to another. Syntax: CAST ( expression AS target_type ); Let's analyze the above syntax: First, specify an expression that can be a constant, a table column, an expression that evaluates to a value.

What does cast mean in PostgreSQL?

Cast is a technique in PostgreSQL with which we can convert a value of one datatype into another. We can perform various cast operations in PostgreSQL for converting one datatype to another, such as the String datatype to the Integer datatype (or the Boolean datatype or datetime datatype) and vice versa.

How do I convert text to integer in PostgreSQL?

SELECT CAST(nullif(<column>, '') AS integer); On the other hand, if you do have NULL values that you need to avoid, try: SELECT CAST(coalesce(<column>, '0') AS integer);

What are Pgadmin casts?

A cast specifies how to convert a value from one data type to another. The Cast dialog organizes the development of a cast through the following dialog tabs: General and Definition. The SQL tab displays the SQL code generated by dialog selections.


1 Answers

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:

  • PostgreSQL: Create index on length of all table fields

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

  • PostgreSQL - CAST vs :: operator on LATERAL table function

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.

like image 136
Erwin Brandstetter Avatar answered Oct 02 '22 14:10

Erwin Brandstetter