Search code examples
apache-flinkflink-sql

Flink - Table SQL API - Add a column to a table


I wonder if there is a way to add a column with constant value to a table in Flink (Java API), something like .withColumn function in Spark DF/DS ?

Regards, Bastien


Solution

  • If you are in a Java environment, this can be done with a simple SELECT query and registering the resulting Table in the catalog.

    // add constant column
    Table withColumn = tEnv.sqlQuery("SELECT a, b, c, 'MyConstant' AS d FROM origTable");
    // register new table
    tEnv.registerTable("tableWithColumn", withColumn);
    
    // query table with constant column
    Table result = tEnv.sqlQuery("SELECT * FROM tableWithColumn");
    

    The first SQL query in not immediately executed. It is more similar to a view definition that is automatically in-lined and optimized together with the second query before execution.