Search code examples
sqldatabaseh2create-table

Quick SQL question: Correct syntax for creating a table with a primary key in H2?


I'm currently starting a new Java application using the H2 database, but I have some confusion about basic SQL use for creating tables. How do I make a table of entries (strings) each with unique, auto-incrementing, non-null, integer primary keys? One of the most basic things to do, but I'm not sure offhand what the correct way to do it with H2 is.

I blame these for my confusion (specifies more than one way of doing the same thing between different databases; can't figure the right way for H2, though): http://www.w3schools.com/Sql/sql_primarykey.asp http://www.w3schools.com/Sql/sql_autoincrement.asp


Solution

  • If I'm reading the H2 documentation correctly, this should work:

    CREATE TABLE MyTableName(PKFieldName IDENTITY PRIMARY KEY, StringFieldName VARCHAR(255))
    

    Basically, you just want to declare your key column to be of type IDENTITY.

    For IDENTITY type see: http://www.h2database.com/html/datatypes.html#identity_type
    For CREATE TABLE syntax see: http://www.h2database.com/html/grammar.html#create_table