Skip to main content
0 reactions

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

SyntaxSQL
value::type
CAST(value AS type)
  • value: the value to convert.
  • type: the data type to convert it to, such as integer, text or date.
  • :: is PostgreSQL’s own short form; CAST is the SQL standard’s.

See Type Casts (opens in a new tab) 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:

TerminalBash
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=#SQL
SELECT '42'::integer;
OutputPlain text
 int4
------
   42
(1 row)

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

Step 3: The Same with CAST

postgres=#SQL
SELECT CAST('42' AS integer);
OutputPlain text
 int4
------
   42
(1 row)

Step 4: Turn a Number into Text

postgres=#SQL
SELECT 42::text;
OutputPlain text
 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.

0 comments