Search code examples
primary-keyh2uuidcreate-table

Specify a default value for a primary key column of type UUID in H2 Database Engine?


This SQL:

CREATE TABLE product_ ( 
    pkey_ UUID PRIMARY KEY
) ; 

…successfully creates a table.

But I want new rows to default to a UUId generated by RANDOM_UUID() as shown on this Answer.

CREATE TABLE product_ ( 
    pkey_ UUID PRIMARY KEY DEFAULT RANDOM_UUID() 
) ; 

But this fails with an error:

org.h2.jdbc.JdbcSQLException: Syntax error in SQL statement "CREATE TABLE PRODUCT_ ( PKEY_ UUID PRIMARY KEY DEFAULT[*] RANDOM_UUID() ) ; "; expected "HASH, AUTO_INCREMENT, NOT, NULL, CHECK, REFERENCES, ,, )"; SQL statement:

What is the cause and solution for this error?


Solution

  • Arguments ordering

    The order in which the arguments appears matters.

    As you can see in the documentation on Column Definition, the syntax chart shows that DEFAULT must appear before the PRIMARY KEY. Swap those two parts to fix.

    CREATE TABLE product_ ( 
        pkey_ UUID DEFAULT RANDOM_UUID() PRIMARY KEY 
    ) ;