Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I convert a character to integer within a PostgreSQL (9.1) function?

I have this following code:

BEGIN
   x := split_part(text, ',', 1);
   UPDATE albumphoto SET order = 1 WHERE idtable = 1 AND idx = x;   
END

But my column table named idx is a numeric type, and the split_part returns a character type to the variable x. I've tried using CAST, but I don't know how to use it properly.

Any ideas?

like image 216
Georgy Passos Avatar asked Feb 07 '13 20:02

Georgy Passos


People also ask

How do I convert character to numeric in PostgreSQL?

Discussion: Use the :: operator to convert strings containing numeric values to the DECIMAL data type. In our example, we converted the string ' 5800.79 ' to 5800.79 (a DECIMAL value). This operator is used to convert between different data types.

How do you change character type in PostgreSQL?

First, specify the name of the table to which the column you want to change belongs in the ALTER TABLE clause. Second, give the name of column whose data type will be changed in the ALTER COLUMN clause. Third, provide the new data type for the column after the TYPE keyword.

How do you handle special characters in PostgreSQL?

Special character symbols are characters with a pre-defined syntactic meaning in PostgreSQL. They are typically disallowed from being used in identifier names for this reason, though as mentioned in the section on quoted identifiers, this restriction can usually be worked around with quotes if need be.

Is int and integer same in PostgreSQL?

There are three kinds of integers in PostgreSQL: Small integer ( SMALLINT ) is 2-byte signed integer that has a range from -32,768 to 32,767. Integer ( INT ) is a 4-byte integer that has a range from -2,147,483,648 to 2,147,483,647.


2 Answers

Like this:

UPDATE albumphoto SET order = 1 WHERE idtable = 1 AND idx = CAST (x AS INTEGER);

(Use appropriate numeric type instead of INTEGER).

like image 162
Anton Kovalenko Avatar answered Sep 27 '22 17:09

Anton Kovalenko


Or simpler:

UPDATE albumphoto
SET    order = 1
WHERE  idtable = 1
AND    idx = split_part(text, ',', 1)::int  -- or whatever type it is
AND    order IS DISTINCT FROM 1;

expression::type is the simple (non-SQL-standard) Postgres way to cast. Details in the manual in the chapter Type Casts.
More about data types in PostgreSQL.

The last predicate I added is useful if order could already be 1, in which case the update wouldn't change anything, but still cost the same. Rather do nothing instead. Related (consider the last paragraph):

  • How do I (or can I) SELECT DISTINCT on multiple columns?

And you don't need a variable here.

like image 44
Erwin Brandstetter Avatar answered Sep 27 '22 16:09

Erwin Brandstetter