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
value::type
CAST(value AS type)
value: the value to convert.type: the data type to convert it to, such asinteger,textordate.::is PostgreSQL’s own short form;CASTis 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:
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
SELECT '42'::integer;
int4
------
42
(1 row)
psql names the column int4, the short name of integer.
Step 3: The Same with CAST
SELECT CAST('42' AS integer);
int4
------
42
(1 row)
Step 4: Turn a Number into Text
SELECT 42::text;
text
------
42
(1 row)
psql lines numbers up on the right and text on the left, which is why 42 moved.
Common Mistakes
| Mistake | What happens | Do this instead |
|---|---|---|
| Casting text that isn’t a number | ERROR: 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