Postgresql 9.6 Error trying to have a function return a string without first casting it as a string.
I am in the progress of learning PostgreSQL (9.6) and am a bit confused by an error I am receiving. If I attempt to create the following function I I receive the following error.
create or replace FUNCTION HelloWorld ()
RETURNS TABLE(HelloCol text, WorldCol text) AS $$
SELECT 'Hello' , 'World' ;
$$
LANGUAGE sql;
Error:
ERROR: return type mismatch in function declared to return record
DETAIL: Final statement returns unknown instead of text at column 1.
CONTEXT: SQL function "helloworld"
SQL state: 42P13
If I cast the text as text it works properly.
create or replace FUNCTION HelloWorld ()
RETURNS TABLE(HelloCol text, WorldCol text) AS $$
SELECT cast('Hello' as text) , cast('World' as Text);
$$
LANGUAGE sql;
I've also tried char(10) and varchar(10) in the first scenario with the same error. I assume I'm just not getting the right variable type in the "TABLE(HelloCol text, WorldCol text)" portion but if 'Hello' isn't text, char, or varchar, what is it? Just some undefined type?
I can change the returned columns to int and have it Select 1,2 and that works just fine without casting.
1 Answer 1
This has been fixed in version 10, as seen in the docs, Type Conversions:
The rules given in the preceding sections will result in assignment of non-unknown data types to all expressions in a SQL query, except for unspecified-type literals that appear as simple output columns of a
SELECT
command. For example, inSELECT 'Hello World';
there is nothing to identify what type the string literal should be taken as. In this situation PostgreSQL will fall back to resolving the literal's type as
text
....
Note
Prior to PostgreSQL 10, this rule did not exist, and unspecified-type literals in aSELECT
output list were left as typeunknown
. That had assorted bad consequences, so it's been changed.
The solutions for you are pretty straight forward:
Either cast the values to text
or upgrade to version 10.
-
Thanks this was informative. I will likely upgrade to version 10 in the future. I wanted to try out DBForge Studio which currently only supports up to 9.6.BGCDC– BGCDC2018年02月27日 15:18:59 +00:00Commented Feb 27, 2018 at 15:18
Explore related questions
See similar questions with these tags.
'Hello'
) and not automatically converted totext
(orvarchar
) by Postgres. Because these literals can be text or dates or other types.SELECT 'Hello'::text , 'World'::text ;