← Back to PostgreSQL, page 2

postgresql-0023 · Easy fresher

How do :: casts and CAST work, and what happens when a value cannot be converted?

value::type and CAST(value AS type) convert values; :: is PostgreSQL shorthand and CAST is standard. A value that cannot be converted raises an error and stops the statement. To clean messy text, test it first with a regular expression, or on PostgreSQL 16+ use pg_input_is_valid.

Full answer

Test data:

sql
CREATE TABLE raw_orders (id int, qty_text text);
INSERT INTO raw_orders VALUES (1, '3'), (2, ' 12 '), (3, 'two'), (4, '');
sql
SELECT id, qty_text::int FROM raw_orders;

Result on PostgreSQL 17:

text
ERROR:  invalid input syntax for type integer: "two"
sql
SELECT id, CASE WHEN trim(qty_text) ~ '^[0-9]+$' THEN trim(qty_text)::int END AS qty, pg_input_is_valid(qty_text, 'integer') AS valid FROM raw_orders ORDER BY id;

Result:

text
 id | qty  | valid
----+------+-------
 1  | 3    | t
 2  | 12   | t
 3  | NULL | f
 4  | NULL | f
(4 rows)
sql
SELECT '2026-12-04'::date + 1 AS tomorrow, CAST('42.50' AS numeric) * 2 AS doubled, 3.7::int AS rounded;

Output:

text
  tomorrow  | doubled | rounded
------------+---------+---------
 2026-12-05 | 85.00   | 4
(1 row)

The plain cast fails on the first bad value with 'invalid input syntax for type integer: "two"', and the whole query returns nothing. The guarded version converts only digit strings, so 'two' and the empty string become NULL. pg_input_is_valid (PostgreSQL 16+) shows that the integer parser itself accepts surrounding spaces in ' 12 '. Casting 3.7 to integer rounds to 4 rather than truncating, a frequent surprise. In import pipelines, load text into a staging table, convert with checks, and report rejected rows.

sql
CREATE TABLE raw_orders (id int, qty_text text);
INSERT INTO raw_orders VALUES (1, '3'), (2, ' 12 '), (3, 'two'), (4, '');

SELECT id, qty_text::int FROM raw_orders;

SELECT id, CASE WHEN trim(qty_text) ~ '^[0-9]+$' THEN trim(qty_text)::int END AS qty, pg_input_is_valid(qty_text, 'integer') AS valid FROM raw_orders ORDER BY id;

SELECT '2026-12-04'::date + 1 AS tomorrow, CAST('42.50' AS numeric) * 2 AS doubled, 3.7::int AS rounded;

Run on PostgreSQL 17.12 (Debian 17.12-0+deb13u1) in a fresh schema, twice, with identical output.

Key points

  • ::type and CAST convert values
  • Bad input raises an error
  • Guard casts with checks
  • pg_input_is_valid in PostgreSQL 16+
  • numeric to int rounds

Common mistakes

  • Casting unvalidated text in production queries
  • Expecting 3.7::int to be 3

Follow-ups

  • How would you report rejected rows during an import?
  • What does pg_input_error_info return?

Tips

  • Show the rounding surprise