I'm often casting query results to user defined types. Consider this simplistic example:
test=# create type test_type as (a int, b int);
CREATE TYPE
test=# create table test_table (a int, b int);
CREATE TABLE
test=# insert into test_table values (1,2);
INSERT 0 1
test=# select r::test_type from (select * from test_table t) as r;
r
-------
(1,2)
(1 row)
For a lot of my queries having a subquery is necessary and that works great. However, sometimes it's a simple 1 to 1 mapping from table to type, like in the example above.
Is there an easier way to express this?
When I try what seems obvious to me I get errors:
test=# select t::test_type from test_table t;
ERROR: cannot cast type test_table to test_type
LINE 1: select t::test_type from test_table t;
^
You can use the ROW construct with wildcard column expansion for this.
regress=> select ROW(t.*)::testtype from testtable t;
row
-------
(1,2)
(1 row)
A bit easier
select t::test_type
from (table test_table) t;
or create your own cast
create function test_table_2_test_type (test_table_value test_table)
returns test_type as $$
select test_table_value.a, test_table_value.b;
$$ language sql;
create cast (test_table as test_type)
with function test_table_2_test_type (test_table);
select t::test_type
from test_table t;
t
-------
(1,2)
http://www.postgresql.org/docs/current/static/sql-createcast.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With