How to specify column types for CTE (Common Table Expressions) in PostgreSQL?

Consider

WITH t (f0, f1) as (
  values 
     (1, 10),
     (2, 20)     
)...

How to indicate that f0 and f1 are of type bigint?

+5
source share
2 answers

I think you will need to specify the types inside the VALUES expression in your case:

WITH t (f0, f1) as (
  values 
     (1::bigint, 10::bigint),
     (2, 20)
)...

You only need the types in the first set of values, PostgreSQL can print the rest.

For example, suppose we have two functions:

create function f(bigint, bigint) returns bigint as $$
begin
    raise notice 'bigint';
    return $1 * $2;
end;
$$ language plpgsql;

create function f(int, int) returns int as $$
begin
    raise notice 'int';
    return $1 * $2;
end;
$$ language plpgsql;

Then

WITH t (f0, f1) as (
    values
        (1, 10),
        (2, 20)
)
select f(f0, f1) from t;

will give you two notifications int, whereas

WITH t (f0, f1) as (
    values
        (1::bigint, 10::bigint),
        (2, 20)
)
select f(f0, f1) from t;

will give you two notifications bigint.

+6
source

I don't know if this will work for you, but the casting of the column you want to specify worked for me in DB2

WITH CTE AS (
SELECT 
    'Apple' AS STRING1
    ,CAST('Orange' AS VARCHAR(10000)) AS STRING2
FROM SYSIBM . SYSDUMMY1)
SELECT * FROM CTE
0
source

All Articles