Available in versions: Dev (3.19) | Latest (3.18) | 3.17 | 3.16 | 3.15 | 3.14 | 3.13 | 3.12 | 3.11 | 3.10 | 3.9

Cast expressions

Applies to ✅ Open Source Edition   ✅ Express Edition   ✅ Professional Edition   ✅ Enterprise Edition

jOOQ's source code generator tries to find the most accurate type mapping between your vendor-specific data types and a matching Java type. For instance, most VARCHAR, CHAR, CLOB types will map to String. Most BINARY, BYTEA, BLOB types will map to byte[]. NUMERIC types will default to java.math.BigDecimal, but can also be any of java.math.BigInteger, java.lang.Long, java.lang.Integer, java.lang.Short, java.lang.Byte, java.lang.Double, java.lang.Float.

Sometimes, this automatic mapping might not be what you needed, or jOOQ cannot know the type of a field. In those cases you would write SQL type CAST like this:

-- Let's say, your Postgres column LAST_NAME was VARCHAR(30)
-- Then you could do this:
SELECT CAST(AUTHOR.LAST_NAME AS TEXT) FROM DUAL

in jOOQ, you can write something like that:

create.select(AUTHOR.LAST_NAME.cast(VARCHAR(100))).fetch();

The same thing can be achieved by casting a Field directly to String.class, as VARCHAR is the default SQLDataType to map to Java's String

create.select(AUTHOR.LAST_NAME.cast(String.class)).fetch();

The complete CAST API in org.jooq.Field consists of these three methods:

public interface Field<T> {

    // Cast this field to the type of another field
    <Z> Field<Z> cast(Field<Z> field);

    // Cast this field to a given DataType
    <Z> Field<Z> cast(DataType<Z> type);

    // Cast this field to the default DataType for a given Class
    <Z> Field<Z> cast(Class<? extends Z> type);
}

// And additional convenience methods in the DSL:
public class DSL {
    <T> Field<T> cast(Object object, Field<T> field);
    <T> Field<T> cast(Object object, DataType<T> type);
    <T> Field<T> cast(Object object, Class<? extends T> type);
    <T> Field<T> castNull(Field<T> field);
    <T> Field<T> castNull(DataType<T> type);
    <T> Field<T> castNull(Class<? extends T> type);
}

Dialect support

This example using jOOQ:

cast("1", VARCHAR(10))

Translates to the following dialect specific expressions:

-- ACCESS
cstr('1')

-- ASE, AURORA_POSTGRES, DB2, DERBY, DUCKDB, EXASOL, FIREBIRD, H2, HANA, HSQLDB, POSTGRES, REDSHIFT, SNOWFLAKE, 
-- SQLDATAWAREHOUSE, SQLITE, SQLSERVER, SYBASE, TERADATA, TRINO, VERTICA, YUGABYTEDB
CAST('1' AS varchar(10))

-- AURORA_MYSQL, MARIADB, MEMSQL, MYSQL
CAST('1' AS char(10))

-- BIGQUERY
CAST('1' AS string)

-- COCKROACHDB
CAST('1' AS string(10))

-- INFORMIX
CAST('1' AS lvarchar(10))

-- ORACLE
CAST('1' AS varchar2(10))

(These are currently generated with jOOQ 3.19, see #10141), or translate your own on our website

References to this page

Feedback

Do you have any feedback about this page? We'd love to hear it!

The jOOQ Logo