Site icon JD Bots

How to Cast a Value to Another Data Type in PostgreSQL

Featured card for How to Cast a Value to Another Data Type in PostgreSQL, with a terminal window listing ‘42’::integer, CAST(‘42’ AS integer), 42::text and the error for ‘abc’::integer.

How to cast a value to another data type in PostgreSQL.

To cast a value to another data type in PostgreSQL, write two colons and the type after it: '42'::integer. CAST('42' AS integer) does the same in standard SQL.

Every command and output on this page is real, from PostgreSQL 19 on macOS.

Syntax

Syntax

value::type
CAST(value AS type)

See Type Casts in the PostgreSQL documentation.

The Example

The text '42' becomes a number, the number 42 becomes text, and the text 'abc' can’t become a number.

Step 1: Connect

Open Terminal and connect to your PostgreSQL server with psql as the postgres user:

Terminal

psql -U postgres

Type the user’s password when psql asks for it. psql connects you to the postgres database, and its prompt is postgres=#.

Step 2: Turn Text into a Number

postgres=#

SELECT '42'::integer;

Output

 int4
------
   42
(1 row)

psql names the column int4, the short name of integer.

Step 3: The Same with CAST

postgres=#

SELECT CAST('42' AS integer);

Output

 int4
------
   42
(1 row)

Step 4: Turn a Number into Text

postgres=#

SELECT 42::text;

Output

 text
------
 42
(1 row)

psql lines numbers up on the right and text on the left, which is why 42 moved.

Common Mistakes

MistakeWhat happensDo this instead
Casting text that isn’t a numberERROR: invalid input syntax for type integer: "abc"Cast only values that fit the type.

FAQ

Which form should I use?

They do the same. :: is shorter; CAST also works in other databases.

Conclusion

Add :: and a type to a value to convert it, or write CAST(value AS type). A value that can’t be converted stops with an error.

Additional Resources

Postgres, PostgreSQL and the Slonik Logo are trademarks or registered trademarks of the PostgreSQL Community Association of Canada, and used with their permission.

Exit mobile version