Re: can't cast varchar as integer?

From: Tom Lane <tgl(at)sss(dot)pgh(dot)pa(dot)us>
To: David Stanaway <david(at)stanaway(dot)net>
Cc: Scott Royston <scroyston(at)mac(dot)com>, pgsql-sql(at)postgresql(dot)org
Subject: Re: can't cast varchar as integer?
Date: 2002-05-14 23:29:10
Message-ID: 1600.1021418950@sss.pgh.pa.us
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-hackers pgsql-sql

David Stanaway <david(at)stanaway(dot)net> writes:
>> LEDEV=3D# select cast(foo as integer) from test;
>> ERROR: Cannot cast type 'character varying' to 'integer'

> scratch=3D# select foo::text::integer from test;
> [works]

> scratch=3D# select int4(foo) from test;
> [works]

For reasons that I don't entirely recall at the moment (but they seemed
good to the pghackers list at the time), cast notations only work if
there is a cast function *exactly* matching the requested cast.
On the other hand, the functional form is laxer because there's an
allowed step of implicit coercion before the function call.

In the case at hand, there's a text->int4 cast function (look in
pg_proc, you'll see int4(text)) but there's no int4(varchar) function.
Also, varchar can be cast to text implicitly --- this is actually
a "binary equivalent" cast requiring no run-time effort. So
select foo::text::integer from test;
works: it's a binary-equivalent cast from varchar to text, followed
by application of int4(text). And
select int4(foo) from test;
works because the same function is found and implicit coercion of
its argument to text succeeds. But
select cast(foo as integer) from test;
doesn't work because there's no declared function int4(varchar).

There's probably not any good reason why there's not int4(varchar),
just that no one got around to making one.

regards, tom lane

In response to

Browse pgsql-hackers by date

  From Date Subject
Next Message Rod Taylor 2002-05-15 01:15:31 Array iterators
Previous Message Tom Lane 2002-05-14 23:15:14 Re: SRF patch (was Re: [HACKERS] troubleshooting pointers)

Browse pgsql-sql by date

  From Date Subject
Next Message Christopher Kings-Lynne 2002-05-15 02:06:36 Re: order by <something wierd>
Previous Message Scott Royston 2002-05-14 23:02:41 Re: [SQL] can't cast varchar as integer?