Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

postgresql

Consider

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

How do I specify that f0 and f1 are of type bigint?

like image 676
John Smith Avatar asked Mar 13 '12 00:03

John Smith


People also ask

Would you use a Common Table Expression CTE )?

CTEs, like database views and derived tables, enable users to more easily write and maintain complex queries via increased readability and simplification. This reduction in complexity is achieved by deconstructing ordinarily complex queries into simple blocks to be used, and reused if necessary, in rewriting the query.

How do I select a specific column in PostgreSQL?

PostgreSQL SELECT statement syntax If you specify a list of columns, you need to place a comma ( , ) between two columns to separate them. If you want to select data from all the columns of the table, you can use an asterisk ( * ) shorthand instead of specifying all the column names.

What is common table expressions CTE in SQL?

Specifies a temporary named result set, known as a common table expression (CTE). This is derived from a simple query and defined within the execution scope of a single SELECT, INSERT, UPDATE, DELETE or MERGE statement. This clause can also be used in a CREATE VIEW statement as part of its defining SELECT statement.


2 Answers

I think you'd have 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 on the first set of values, PostgreSQL can infer 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 int notices whereas

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

would give you two bigint notices.

like image 163
mu is too short Avatar answered Oct 01 '22 18:10

mu is too short


I don't know if this will work for you, but casting 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
like image 45
scott.se Avatar answered Oct 01 '22 19:10

scott.se