H2 Database Engine: Version 2.1.214 (2022-06-13)
H2 Database Engine: Version 2.1.214 (2022-06-13)
H2 Database Engine: Version 2.1.214 (2022-06-13)
1 of 428
Table of Contents
Quickstart................................................................................................. 25
Embedding H2 in an Application...........................................................25
The H2 Console Application...................................................................25
Step-by-Step...................................................................................... 25
Installation...................................................................................... 25
Start the Console............................................................................26
Login............................................................................................... 26
Sample............................................................................................ 27
Execute........................................................................................... 28
Disconnect...................................................................................... 29
End................................................................................................. 29
Installation............................................................................................... 30
Requirements........................................................................................ 30
Database Engine................................................................................ 30
H2 Console......................................................................................... 30
Supported Platforms.............................................................................. 30
Installing the Software..........................................................................30
Directory Structure................................................................................ 30
Tutorial..................................................................................................... 32
Starting and Using the H2 Console........................................................32
Firewall.............................................................................................. 34
Testing Java....................................................................................... 34
Error Message 'Port may be in use'....................................................34
Using another Port.............................................................................34
Connecting to the Server using a Browser.........................................35
Multiple Concurrent Sessions.............................................................35
Login.................................................................................................. 35
Error Messages..................................................................................35
Adding Database Drivers...................................................................35
Using the H2 Console.........................................................................36
Inserting Table Names or Column Names..........................................36
Disconnecting and Stopping the Application......................................36
Special H2 Console Syntax....................................................................36
Settings of the H2 Console....................................................................38
Connecting to a Database using JDBC...................................................38
Creating New Databases.......................................................................39
Using the Server.................................................................................... 40
Starting the Server Tool from Command Line....................................41
Connecting to the TCP Server............................................................41
Starting the TCP Server within an Application....................................41
Stopping a TCP Server from Another Process.....................................41
2 of 428
Using Hibernate....................................................................................42
Using TopLink and Glassfish..................................................................42
Using EclipseLink................................................................................... 43
Using Apache ActiveMQ........................................................................43
Using H2 within NetBeans.....................................................................43
Using H2 with jOOQ............................................................................... 44
Using Databases in Web Applications....................................................45
Embedded Mode................................................................................45
Server Mode....................................................................................... 45
Using a Servlet Listener to Start and Stop a Database.......................45
Using the H2 Console Servlet.............................................................47
CSV (Comma Separated Values) Support..............................................48
Reading a CSV File from Within a Database.......................................48
Importing Data from a CSV File..........................................................48
Writing a CSV File from Within a Database.........................................48
Writing a CSV File from a Java Application.........................................49
Reading a CSV File from a Java Application........................................49
Upgrade, Backup, and Restore..............................................................50
Database Upgrade.............................................................................50
Backup using the Script Tool..............................................................50
Restore from a Script.........................................................................50
Online Backup.................................................................................... 51
Command Line Tools............................................................................. 51
The Shell Tool........................................................................................ 52
Using OpenOffice Base.......................................................................... 53
Java Web Start / JNLP............................................................................. 54
Using a Connection Pool........................................................................ 54
Fulltext Search...................................................................................... 55
Using the Native Fulltext Search........................................................55
Using the Apache Lucene Fulltext Search..........................................56
User-Defined Variables.......................................................................... 57
Date and Time....................................................................................... 58
Using Spring.......................................................................................... 59
Using the TCP Server.........................................................................59
OSGi...................................................................................................... 59
Java Management Extension (JMX)........................................................59
Features................................................................................................... 61
Feature List........................................................................................... 62
Main Features....................................................................................62
Additional Features............................................................................62
SQL Support....................................................................................... 62
Security Features............................................................................... 63
Other Features and Tools...................................................................63
H2 in Use............................................................................................... 64
3 of 428
Connection Modes................................................................................. 64
Embedded Mode................................................................................64
Server Mode....................................................................................... 65
Mixed Mode........................................................................................ 65
Database URL Overview........................................................................66
Connecting to an Embedded (Local) Database......................................68
In-Memory Databases...........................................................................68
Database Files Encryption.....................................................................69
Creating a New Database with File Encryption...................................69
Connecting to an Encrypted Database...............................................69
Encrypting or Decrypting a Database.................................................69
Database File Locking...........................................................................70
Opening a Database Only if it Already Exists.........................................70
Closing a Database...............................................................................71
Delayed Database Closing.................................................................71
Don't Close a Database when the VM Exits........................................71
Execute SQL on Connection..................................................................72
Ignore Unknown Settings......................................................................72
Changing Other Settings when Opening a Connection..........................72
Custom File Access Mode......................................................................73
Multiple Connections............................................................................. 73
Opening Multiple Databases at the Same Time..................................73
Multiple Connections to the Same Database: Client/Server................73
Multithreading Support......................................................................73
Locking, Lock-Timeout, Deadlocks.....................................................74
Database File Layout............................................................................. 74
Moving and Renaming Database Files................................................75
Backup............................................................................................... 76
Logging and Recovery........................................................................... 76
Compatibility......................................................................................... 76
Compatibility Modes........................................................................... 76
REGULAR Compatibility mode............................................................76
STRICT Compatibility Mode................................................................77
LEGACY Compatibility Mode...............................................................77
DB2 Compatibility Mode..................................................................... 78
Derby Compatibility Mode..................................................................79
HSQLDB Compatibility Mode..............................................................79
MS SQL Server Compatibility Mode....................................................79
MariaDB Compatibility Mode..............................................................80
MySQL Compatibility Mode................................................................. 81
Oracle Compatibility Mode.................................................................82
PostgreSQL Compatibility Mode.........................................................83
Auto-Reconnect..................................................................................... 84
Automatic Mixed Mode.......................................................................... 84
4 of 428
Page Size.............................................................................................. 86
Using the Trace Options........................................................................86
Trace Options..................................................................................... 86
Setting the Maximum Size of the Trace File.......................................86
Java Code Generation........................................................................87
Using Other Logging APIs......................................................................87
Read Only Databases............................................................................88
Read Only Databases in Zip or Jar File...................................................88
Opening a Corrupted Database..........................................................89
Generated Columns (Computed Columns) / Function Based Index........89
Multi-Dimensional Indexes....................................................................90
User-Defined Functions and Stored Procedures.....................................90
Referencing a Compiled Method........................................................91
Declaring Functions as Source Code..................................................91
Method Overloading........................................................................... 92
Function Data Type Mapping..............................................................92
Functions That Require a Connection.................................................93
Functions Throwing an Exception.......................................................93
Functions Returning a Result Set.......................................................93
Using SimpleResultSet.......................................................................93
Using a Function as a Table...............................................................94
Pluggable or User-Defined Tables..........................................................95
Triggers................................................................................................. 96
Compacting a Database........................................................................97
Cache Settings...................................................................................... 98
External authentication (Experimental).................................................98
Securing your H2.................................................................................... 101
Introduction......................................................................................... 101
Network exposed................................................................................101
Alias / Stored procedures....................................................................101
Grants / Roles / Permissions................................................................101
Encrypted storage............................................................................... 101
Performance........................................................................................... 103
Performance Comparison....................................................................103
Embedded........................................................................................ 103
Client-Server.................................................................................... 104
Benchmark Results and Comments..................................................105
H2................................................................................................. 105
HSQLDB........................................................................................ 105
Derby............................................................................................ 105
PostgreSQL...................................................................................106
MySQL........................................................................................... 106
SQLite........................................................................................... 106
Firebird......................................................................................... 107
5 of 428
Why Oracle / MS SQL Server / DB2 are Not Listed.........................107
About this Benchmark......................................................................107
How to Run................................................................................... 107
Separate Process per Database....................................................107
Number of Connections.................................................................107
Real-World Tests........................................................................... 107
Comparing Embedded with Server Databases..............................108
Test Platform................................................................................108
Multiple Runs................................................................................108
Memory Usage.............................................................................. 108
Delayed Operations......................................................................108
Transaction Commit / Durability....................................................108
Using Prepared Statements..........................................................109
Currently Not Tested: Startup Time..............................................109
PolePosition Benchmark......................................................................109
Database Performance Tuning............................................................110
Keep Connections Open or Use a Connection Pool...........................110
Use a Modern JVM............................................................................111
Virus Scanners.................................................................................111
Using the Trace Options...................................................................111
Index Usage..................................................................................... 111
Index Hints....................................................................................... 112
How Data is Stored Internally...........................................................112
Optimizer......................................................................................... 113
Expression Optimization...................................................................113
COUNT(*) Optimization....................................................................113
Updating Optimizer Statistics / Column Selectivity...........................113
In-Memory (Hash) Indexes...............................................................114
Use Prepared Statements................................................................114
Prepared Statements and IN(...).......................................................114
Optimization Examples....................................................................115
Cache Size and Type........................................................................115
Data Types....................................................................................... 115
Sorted Insert Optimization...............................................................115
Using the Built-In Profiler.....................................................................116
Application Profiling............................................................................116
Analyze First....................................................................................116
Database Profiling............................................................................... 117
Statement Execution Plans..................................................................118
Displaying the Scan Count...............................................................119
Special Optimizations....................................................................... 119
How Data is Stored and How Indexes Work.........................................120
Indexes............................................................................................ 121
Using Multiple Indexes.....................................................................122
6 of 428
Fast Database Import.......................................................................... 123
Advanced............................................................................................... 124
Result Sets.......................................................................................... 125
Statements that Return a Result Set................................................125
Limiting the Number of Rows...........................................................125
Large Result Sets and External Sorting............................................125
Large Objects...................................................................................... 125
Storing and Reading Large Objects..................................................125
When to use CLOB/BLOB..................................................................125
Linked Tables...................................................................................... 126
Updatable Views.................................................................................127
Transaction Isolation...........................................................................127
Multi-Version Concurrency Control (MVCC)......................................128
Lock Timeout...................................................................................129
Clustering / High Availability...............................................................129
Using the CreateCluster Tool............................................................130
Detect Which Cluster Instances are Running....................................131
Clustering Algorithm and Limitations...............................................131
Two Phase Commit.............................................................................. 132
Compatibility....................................................................................... 132
Transaction Commit when Autocommit is On...................................132
Keywords / Reserved Words................................................................133
Standards Compliance........................................................................137
Supported Character Sets, Character Encoding, and Unicode..........137
Run as Windows Service.....................................................................137
Install the Service............................................................................138
Start the Service..............................................................................138
Connect to the H2 Console...............................................................138
Stop the Service............................................................................... 138
Uninstall the Service........................................................................138
Additional JDBC drivers....................................................................139
ODBC Driver........................................................................................ 139
ODBC Installation.............................................................................139
Starting the Server........................................................................... 139
ODBC Configuration.........................................................................140
PG Protocol Support Limitations.......................................................141
Security Considerations...................................................................141
Using Microsoft Access..................................................................... 141
ACID.................................................................................................... 141
Atomicity.......................................................................................... 142
Consistency...................................................................................... 142
Isolation........................................................................................... 142
Durability......................................................................................... 142
Durability Problems............................................................................. 142
7 of 428
Ways to (Not) Achieve Durability.....................................................143
Running the Durability Test..............................................................144
Using the Recover Tool.......................................................................144
File Locking Protocols.......................................................................... 145
File Locking Method 'File'.................................................................146
File Locking Method 'Socket'............................................................147
File Locking Method 'FS'...................................................................147
Using Passwords.................................................................................148
Using Secure Passwords...................................................................148
Passwords: Using Char Arrays instead of Strings..............................148
Passing the User Name and/or Password in the URL........................149
Password Hash.................................................................................... 149
Protection against SQL Injection..........................................................150
What is SQL Injection.......................................................................150
Disabling Literals.............................................................................. 150
Using Constants...............................................................................151
Using the ZERO() Function...............................................................151
Protection against Remote Access......................................................152
Restricting Class Loading and Usage...................................................152
Security Protocols...............................................................................153
User Password Encryption................................................................153
File Encryption.................................................................................154
Wrong Password / User Name Delay................................................155
HTTPS Connections..........................................................................155
TLS Connections.................................................................................. 155
Universally Unique Identifiers (UUID)..................................................156
Spatial Features..................................................................................157
Recursive Queries...............................................................................158
Settings Read from System Properties................................................159
Setting the Server Bind Address..........................................................159
Pluggable File System.........................................................................159
Split File System.................................................................................. 161
Java Objects Serialization....................................................................161
Limits and Limitations.........................................................................162
Glossary and Links..............................................................................163
Commands............................................................................................. 165
Index................................................................................................... 165
Commands (Data Manipulation).......................................................165
Commands (Data Definition)............................................................165
Commands (Other)..........................................................................167
Details................................................................................................. 168
Commands (Data Manipulation)..........................................................168
SELECT............................................................................................. 168
INSERT............................................................................................. 171
8 of 428
UPDATE............................................................................................ 171
DELETE............................................................................................ 171
BACKUP............................................................................................ 172
CALL................................................................................................. 172
EXECUTE IMMEDIATE.......................................................................172
EXPLAIN........................................................................................... 173
MERGE INTO..................................................................................... 173
MERGE USING..................................................................................173
RUNSCRIPT....................................................................................... 174
SCRIPT............................................................................................. 175
SHOW............................................................................................... 176
Explicit table....................................................................................176
Table value......................................................................................177
WITH................................................................................................ 177
Commands (Data Definition)...............................................................178
ALTER DOMAIN................................................................................. 178
ALTER DOMAIN ADD CONSTRAINT...................................................179
ALTER DOMAIN DROP CONSTRAINT.................................................179
ALTER DOMAIN RENAME..................................................................179
ALTER DOMAIN RENAME CONSTRAINT.............................................179
ALTER INDEX RENAME...................................................................... 180
ALTER SCHEMA RENAME..................................................................180
ALTER SEQUENCE............................................................................180
ALTER TABLE ADD............................................................................ 180
ALTER TABLE ADD CONSTRAINT......................................................181
ALTER TABLE RENAME CONSTRAINT................................................181
ALTER TABLE ALTER COLUMN..........................................................182
ALTER TABLE DROP COLUMN...........................................................183
ALTER TABLE DROP CONSTRAINT.....................................................184
ALTER TABLE SET............................................................................. 184
ALTER TABLE RENAME.....................................................................184
ALTER USER ADMIN.......................................................................... 185
ALTER USER RENAME.......................................................................185
ALTER USER SET PASSWORD...........................................................185
ALTER VIEW RECOMPILE..................................................................186
ALTER VIEW RENAME.......................................................................186
ANALYZE.......................................................................................... 186
COMMENT ON..................................................................................187
CREATE AGGREGATE........................................................................ 187
CREATE ALIAS..................................................................................187
CREATE CONSTANT.......................................................................... 189
CREATE DOMAIN..............................................................................189
CREATE INDEX.................................................................................190
CREATE LINKED TABLE.....................................................................190
9 of 428
CREATE ROLE................................................................................... 191
CREATE SCHEMA.............................................................................. 192
CREATE SEQUENCE..........................................................................192
CREATE TABLE.................................................................................193
CREATE TRIGGER.............................................................................194
CREATE USER................................................................................... 196
CREATE VIEW................................................................................... 196
DROP AGGREGATE...........................................................................197
DROP ALIAS...................................................................................... 197
DROP ALL OBJECTS..........................................................................197
DROP CONSTANT.............................................................................198
DROP DOMAIN.................................................................................. 198
DROP INDEX..................................................................................... 198
DROP ROLE......................................................................................198
DROP SCHEMA.................................................................................199
DROP SEQUENCE.............................................................................199
DROP TABLE..................................................................................... 199
DROP TRIGGER................................................................................. 200
DROP USER...................................................................................... 200
DROP VIEW......................................................................................200
TRUNCATE TABLE............................................................................. 200
Commands (Other).............................................................................. 201
CHECKPOINT....................................................................................201
CHECKPOINT SYNC........................................................................... 201
COMMIT............................................................................................ 201
COMMIT TRANSACTION....................................................................202
GRANT RIGHT................................................................................... 202
GRANT ALTER ANY SCHEMA.............................................................202
GRANT ROLE....................................................................................203
HELP................................................................................................ 203
PREPARE COMMIT............................................................................203
REVOKE RIGHT................................................................................. 203
REVOKE ALTER ANY SCHEMA...........................................................204
REVOKE ROLE..................................................................................204
ROLLBACK........................................................................................ 204
ROLLBACK TRANSACTION................................................................204
SAVEPOINT....................................................................................... 205
SET @.............................................................................................. 205
SET ALLOW_LITERALS......................................................................205
SET AUTOCOMMIT............................................................................ 206
SET CACHE_SIZE..............................................................................206
SET CLUSTER...................................................................................207
SET BUILTIN_ALIAS_OVERRIDE.........................................................207
SET CATALOG................................................................................... 207
10 of 428
SET COLLATION................................................................................ 208
SET DATABASE_EVENT_LISTENER....................................................208
SET DB_CLOSE_DELAY.....................................................................209
SET DEFAULT_LOCK_TIMEOUT..........................................................209
SET DEFAULT_NULL_ORDERING.......................................................210
SET DEFAULT_TABLE_TYPE...............................................................210
SET EXCLUSIVE................................................................................211
SET IGNORECASE.............................................................................211
SET IGNORE_CATALOGS...................................................................212
SET JAVA_OBJECT_SERIALIZER..........................................................212
SET LAZY_QUERY_EXECUTION..........................................................212
SET LOCK_MODE..............................................................................213
SET LOCK_TIMEOUT.........................................................................213
SET MAX_LENGTH_INPLACE_LOB......................................................214
SET MAX_LOG_SIZE..........................................................................214
SET MAX_MEMORY_ROWS................................................................214
SET MAX_MEMORY_UNDO................................................................215
SET MAX_OPERATION_MEMORY.......................................................215
SET MODE........................................................................................ 216
SET NON_KEYWORDS.......................................................................216
SET OPTIMIZE_REUSE_RESULTS.......................................................216
SET PASSWORD...............................................................................217
SET QUERY_STATISTICS...................................................................217
SET QUERY_STATISTICS_MAX_ENTRIES............................................217
SET QUERY_TIMEOUT.......................................................................218
SET REFERENTIAL_INTEGRITY...........................................................218
SET RETENTION_TIME....................................................................... 218
SET SALT HASH................................................................................219
SET SCHEMA....................................................................................219
SET SCHEMA_SEARCH_PATH............................................................220
SET SESSION CHARACTERISTICS......................................................220
SET THROTTLE.................................................................................220
SET TIME ZONE................................................................................221
SET TRACE_LEVEL............................................................................221
SET TRACE_MAX_FILE_SIZE..............................................................221
SET TRUNCATE_LARGE_LENGTH.......................................................222
SET VARIABLE_BINARY.....................................................................222
SET WRITE_DELAY............................................................................ 222
SHUTDOWN...................................................................................... 223
Functions................................................................................................ 224
Index................................................................................................... 224
Numeric Functions...........................................................................224
String Functions............................................................................... 225
Time and Date Functions.................................................................226
11 of 428
System Functions............................................................................. 227
JSON Functions................................................................................. 228
Table Functions................................................................................ 228
Details................................................................................................. 229
Numeric Functions..............................................................................229
ABS.................................................................................................. 229
ACOS................................................................................................ 229
ASIN................................................................................................. 229
ATAN................................................................................................ 230
COS.................................................................................................. 230
COSH............................................................................................... 230
COT.................................................................................................. 230
SIN................................................................................................... 231
SINH................................................................................................. 231
TAN.................................................................................................. 231
TANH................................................................................................ 231
ATAN2.............................................................................................. 231
BITAND............................................................................................. 232
BITOR............................................................................................... 232
BITXOR............................................................................................. 232
BITNOT............................................................................................. 233
BITNAND.......................................................................................... 233
BITNOR............................................................................................233
BITXNOR..........................................................................................233
BITGET............................................................................................. 234
BITCOUNT........................................................................................ 234
LSHIFT.............................................................................................. 234
RSHIFT............................................................................................. 235
ULSHIFT...........................................................................................235
URSHIFT........................................................................................... 236
ROTATELEFT....................................................................................236
ROTATERIGHT.................................................................................. 236
MOD................................................................................................. 237
CEIL.................................................................................................. 237
DEGREES.......................................................................................... 237
EXP.................................................................................................. 237
FLOOR.............................................................................................. 238
LN.................................................................................................... 238
LOG.................................................................................................. 238
LOG10.............................................................................................. 238
ORA_HASH....................................................................................... 239
RADIANS.......................................................................................... 239
SQRT................................................................................................ 239
PI...................................................................................................... 239
12 of 428
POWER............................................................................................. 240
RAND............................................................................................... 240
RANDOM_UUID................................................................................. 240
ROUND............................................................................................. 240
SECURE_RAND.................................................................................241
SIGN................................................................................................. 241
ENCRYPT.......................................................................................... 241
DECRYPT.......................................................................................... 241
HASH................................................................................................ 242
TRUNC.............................................................................................. 242
COMPRESS....................................................................................... 243
EXPAND............................................................................................ 243
ZERO................................................................................................ 243
String Functions..................................................................................243
ASCII................................................................................................ 243
BIT_LENGTH..................................................................................... 244
CHAR_LENGTH.................................................................................244
OCTET_LENGTH................................................................................ 244
CHAR................................................................................................ 244
CONCAT........................................................................................... 245
CONCAT_WS..................................................................................... 245
DIFFERENCE..................................................................................... 245
HEXTORAW...................................................................................... 246
RAWTOHEX...................................................................................... 246
INSERT Function............................................................................... 246
LOWER............................................................................................. 246
UPPER.............................................................................................. 246
LEFT................................................................................................. 247
RIGHT............................................................................................... 247
LOCATE............................................................................................ 247
LPAD................................................................................................ 247
RPAD................................................................................................ 248
LTRIM............................................................................................... 248
RTRIM............................................................................................... 248
TRIM................................................................................................. 248
REGEXP_REPLACE............................................................................249
REGEXP_LIKE.................................................................................... 249
REGEXP_SUBSTR..............................................................................250
REPEAT............................................................................................ 250
REPLACE..........................................................................................251
SOUNDEX......................................................................................... 251
SPACE.............................................................................................. 251
STRINGDECODE...............................................................................251
STRINGENCODE...............................................................................252
13 of 428
STRINGTOUTF8................................................................................252
SUBSTRING...................................................................................... 252
UTF8TOSTRING................................................................................252
QUOTE_IDENT..................................................................................253
XMLATTR.......................................................................................... 253
XMLNODE......................................................................................... 253
XMLCOMMENT.................................................................................. 253
XMLCDATA....................................................................................... 254
XMLSTARTDOC................................................................................. 254
XMLTEXT.......................................................................................... 254
TO_CHAR.......................................................................................... 254
TRANSLATE...................................................................................... 255
Time and Date Functions..................................................................... 255
CURRENT_DATE...............................................................................255
CURRENT_TIME................................................................................255
CURRENT_TIMESTAMP......................................................................256
LOCALTIME....................................................................................... 256
LOCALTIMESTAMP............................................................................257
DATEADD......................................................................................... 257
DATEDIFF......................................................................................... 258
DATE_TRUNC.................................................................................... 258
DAYNAME......................................................................................... 258
DAY_OF_MONTH............................................................................... 258
DAY_OF_WEEK.................................................................................. 259
ISO_DAY_OF_WEEK........................................................................... 259
DAY_OF_YEAR..................................................................................259
EXTRACT.......................................................................................... 259
FORMATDATETIME...........................................................................260
HOUR............................................................................................... 260
MINUTE............................................................................................ 260
MONTH............................................................................................. 260
MONTHNAME.................................................................................... 261
PARSEDATETIME..............................................................................261
QUARTER.........................................................................................261
SECOND........................................................................................... 262
WEEK............................................................................................... 262
ISO_WEEK........................................................................................ 262
YEAR................................................................................................ 262
ISO_YEAR.........................................................................................263
System Functions................................................................................ 263
ABORT_SESSION..............................................................................263
ARRAY_GET...................................................................................... 263
CARDINALITY.................................................................................... 264
ARRAY_CONTAINS............................................................................264
14 of 428
ARRAY_CAT...................................................................................... 264
ARRAY_APPEND................................................................................ 264
ARRAY_MAX_CARDINALITY...............................................................265
TRIM_ARRAY..................................................................................... 265
ARRAY_SLICE.................................................................................... 265
AUTOCOMMIT................................................................................... 265
CANCEL_SESSION............................................................................. 266
CASEWHEN Function........................................................................266
COALESCE........................................................................................ 266
CONVERT......................................................................................... 266
CURRVAL.......................................................................................... 267
CSVWRITE........................................................................................ 267
CURRENT_SCHEMA........................................................................... 268
CURRENT_CATALOG.........................................................................268
DATABASE_PATH.............................................................................. 268
DATA_TYPE_SQL............................................................................... 268
DB_OBJECT_ID.................................................................................. 269
DB_OBJECT_SQL...............................................................................270
DECODE........................................................................................... 270
DISK_SPACE_USED...........................................................................270
SIGNAL............................................................................................. 271
ESTIMATED_ENVELOPE..................................................................... 271
FILE_READ........................................................................................ 271
FILE_WRITE......................................................................................272
GREATEST........................................................................................ 272
LEAST............................................................................................... 272
LOCK_MODE..................................................................................... 272
LOCK_TIMEOUT................................................................................273
MEMORY_FREE................................................................................. 273
MEMORY_USED................................................................................273
NEXTVAL.......................................................................................... 273
NULLIF.............................................................................................. 274
NVL2................................................................................................ 274
READONLY....................................................................................... 274
ROWNUM.........................................................................................275
SESSION_ID...................................................................................... 275
SET................................................................................................... 275
TRANSACTION_ID.............................................................................276
TRUNCATE_VALUE............................................................................ 276
CURRENT_PATH................................................................................ 276
CURRENT_ROLE................................................................................ 276
CURRENT_USER...............................................................................277
H2VERSION...................................................................................... 277
JSON Functions.................................................................................... 277
15 of 428
JSON_OBJECT.................................................................................... 277
JSON_ARRAY..................................................................................... 277
Table Functions................................................................................... 278
CSVREAD......................................................................................... 278
LINK_SCHEMA................................................................................... 279
TABLE..............................................................................................279
UNNEST............................................................................................ 280
Aggregate Functions..............................................................................281
Index................................................................................................... 281
General Aggregate Functions...........................................................281
Binary Set Functions........................................................................281
Ordered Aggregate Functions..........................................................282
Hypothetical Set Functions...............................................................282
Inverse Distribution Functions..........................................................282
JSON Aggregate Functions...............................................................282
Details................................................................................................. 282
General Aggregate Functions..............................................................282
AVG.................................................................................................. 282
MAX................................................................................................. 283
MIN.................................................................................................. 283
SUM................................................................................................. 283
EVERY.............................................................................................. 284
ANY.................................................................................................. 284
COUNT............................................................................................. 284
STDDEV_POP.................................................................................... 285
STDDEV_SAMP.................................................................................285
VAR_POP.......................................................................................... 285
VAR_SAMP........................................................................................ 285
BIT_AND_AGG..................................................................................286
BIT_OR_AGG..................................................................................... 286
BIT_XOR_AGG................................................................................... 286
BIT_NAND_AGG................................................................................287
BIT_NOR_AGG..................................................................................287
BIT_XNOR_AGG................................................................................287
ENVELOPE........................................................................................ 287
Binary Set Functions...........................................................................288
COVAR_POP...................................................................................... 288
COVAR_SAMP................................................................................... 288
CORR............................................................................................... 288
REGR_SLOPE.................................................................................... 289
REGR_INTERCEPT............................................................................. 289
REGR_COUNT................................................................................... 289
REGR_R2.......................................................................................... 290
REGR_AVGX..................................................................................... 290
16 of 428
REGR_AVGY...................................................................................... 290
REGR_SXX........................................................................................ 291
REGR_SYY........................................................................................ 291
REGR_SXY........................................................................................ 291
Ordered Aggregate Functions.............................................................291
LISTAGG........................................................................................... 291
ARRAY_AGG.....................................................................................292
Hypothetical Set Functions..................................................................293
RANK aggregate............................................................................... 293
DENSE_RANK aggregate..................................................................293
PERCENT_RANK aggregate...............................................................293
CUME_DIST aggregate.....................................................................294
Inverse Distribution Functions.............................................................294
PERCENTILE_CONT...........................................................................294
PERCENTILE_DISC............................................................................295
MEDIAN............................................................................................ 295
MODE............................................................................................... 295
JSON Aggregate Functions...................................................................296
JSON_OBJECTAGG............................................................................. 296
JSON_ARRAYAGG.............................................................................. 296
Window Functions..................................................................................298
Index................................................................................................... 298
Row Number Function......................................................................298
Rank Functions................................................................................. 298
Lead or Lag Functions......................................................................298
Nth Value Functions.........................................................................298
Other Window Functions..................................................................298
Details................................................................................................. 298
Row Number Function.........................................................................298
ROW_NUMBER.................................................................................. 298
Rank Functions.................................................................................... 299
RANK................................................................................................ 299
DENSE_RANK.................................................................................... 299
PERCENT_RANK................................................................................ 300
CUME_DIST....................................................................................... 300
Lead or Lag Functions.........................................................................301
LEAD................................................................................................ 301
LAG.................................................................................................. 301
Nth Value Functions............................................................................302
FIRST_VALUE.................................................................................... 302
LAST_VALUE..................................................................................... 302
NTH_VALUE...................................................................................... 303
Other Window Functions.....................................................................303
NTILE................................................................................................ 303
17 of 428
RATIO_TO_REPORT........................................................................... 304
Data Types............................................................................................. 305
Index................................................................................................... 305
Details................................................................................................. 306
CHARACTER........................................................................................ 306
CHARACTER VARYING.........................................................................306
CHARACTER LARGE OBJECT................................................................307
VARCHAR_IGNORECASE......................................................................308
BINARY................................................................................................ 308
BINARY VARYING.................................................................................309
BINARY LARGE OBJECT........................................................................309
BOOLEAN............................................................................................ 309
TINYINT............................................................................................... 310
SMALLINT............................................................................................ 310
INTEGER.............................................................................................. 310
BIGINT................................................................................................. 311
NUMERIC............................................................................................. 311
REAL.................................................................................................... 311
DOUBLE PRECISION............................................................................. 312
DECFLOAT........................................................................................... 312
DATE................................................................................................... 312
TIME.................................................................................................... 313
TIME WITH TIME ZONE......................................................................... 314
TIMESTAMP.........................................................................................314
TIMESTAMP WITH TIME ZONE..............................................................315
INTERVAL............................................................................................ 316
JAVA_OBJECT....................................................................................... 316
ENUM.................................................................................................. 317
GEOMETRY.......................................................................................... 317
JSON.................................................................................................... 318
UUID.................................................................................................... 319
ARRAY................................................................................................. 319
ROW.................................................................................................... 320
Interval Data Types............................................................................. 320
INTERVAL YEAR................................................................................320
INTERVAL MONTH............................................................................320
INTERVAL DAY.................................................................................. 320
INTERVAL HOUR............................................................................... 321
INTERVAL MINUTE............................................................................321
INTERVAL SECOND...........................................................................321
INTERVAL YEAR TO MONTH..............................................................322
INTERVAL DAY TO HOUR..................................................................322
INTERVAL DAY TO MINUTE...............................................................322
INTERVAL DAY TO SECOND..............................................................323
18 of 428
INTERVAL HOUR TO MINUTE............................................................323
INTERVAL HOUR TO SECOND...........................................................323
INTERVAL MINUTE TO SECOND........................................................323
SQL Grammar......................................................................................... 325
Index................................................................................................... 325
Literals............................................................................................. 325
Datetime fields................................................................................. 326
Other Grammar................................................................................ 326
Details................................................................................................. 329
Literals................................................................................................ 329
Value................................................................................................ 329
Approximate numeric....................................................................... 329
Array................................................................................................ 329
Boolean............................................................................................ 330
Bytes................................................................................................ 330
Date................................................................................................. 330
Date and time.................................................................................. 330
Dollar Quoted String........................................................................331
Exact numeric.................................................................................. 331
Hex Number..................................................................................... 331
Int.................................................................................................... 331
GEOMETRY....................................................................................... 332
JSON................................................................................................. 332
Long................................................................................................. 332
Null.................................................................................................. 333
Number............................................................................................ 333
Numeric........................................................................................... 333
String............................................................................................... 333
UUID................................................................................................ 334
Time................................................................................................. 334
Time with time zone......................................................................... 334
Timestamp....................................................................................... 335
Timestamp with time zone...............................................................335
Interval............................................................................................335
INTERVAL YEAR................................................................................336
INTERVAL MONTH............................................................................336
INTERVAL DAY.................................................................................. 336
INTERVAL HOUR............................................................................... 336
INTERVAL MINUTE............................................................................336
INTERVAL SECOND...........................................................................337
INTERVAL YEAR TO MONTH..............................................................337
INTERVAL DAY TO HOUR..................................................................337
INTERVAL DAY TO MINUTE...............................................................337
INTERVAL DAY TO SECOND..............................................................338
19 of 428
INTERVAL HOUR TO MINUTE............................................................338
INTERVAL HOUR TO SECOND...........................................................338
INTERVAL MINUTE TO SECOND........................................................338
Datetime fields.................................................................................... 339
Datetime field.................................................................................. 339
Year field.......................................................................................... 339
Month field....................................................................................... 339
Day of month field...........................................................................340
Hour field......................................................................................... 340
Minute field...................................................................................... 340
Second field.....................................................................................340
Timezone hour field.........................................................................340
Timezone minute field...................................................................... 341
Timezone second field.....................................................................341
Millennium field................................................................................ 341
Century field.................................................................................... 341
Decade field..................................................................................... 341
Quarter field..................................................................................... 342
Millisecond field...............................................................................342
Microsecond field.............................................................................342
Nanosecond field.............................................................................342
Day of year field............................................................................... 342
ISO day of week field.......................................................................343
ISO week field.................................................................................. 343
ISO week year field..........................................................................343
Day of week field.............................................................................343
Week field........................................................................................ 344
Week year field................................................................................ 344
Epoch field....................................................................................... 344
Other Grammar................................................................................... 344
Alias................................................................................................. 344
And Condition..................................................................................345
Array element reference..................................................................345
Field reference................................................................................. 345
Array value constructor by query.....................................................345
Case expression............................................................................... 346
Simple case...................................................................................... 346
Searched case.................................................................................. 346
Cast specification............................................................................. 347
Cipher.............................................................................................. 347
Column Definition............................................................................347
Column Constraint Definition...........................................................348
Comment......................................................................................... 349
Bracketed comment......................................................................... 349
20 of 428
Compare.......................................................................................... 350
Condition.......................................................................................... 350
Condition Right Hand Side...............................................................350
Comparison Right Hand Side............................................................351
Quantified Comparison Right Hand Side..........................................351
Null Predicate Right Hand Side.........................................................352
Distinct Predicate Right Hand Side...................................................352
Quantified Distinct Predicate Right Hand Side..................................352
Boolean Test Right Hand Side..........................................................353
Type Predicate Right Hand Side.......................................................353
JSON Predicate Right Hand Side.......................................................354
Between Predicate Right Hand Side.................................................354
In Predicate Right Hand Side............................................................354
Like Predicate Right Hand Side........................................................355
Regexp Predicate Right Hand Side...................................................355
Table Constraint Definition...............................................................355
Constraint Name Definition..............................................................356
Csv Options...................................................................................... 356
Data Change Delta Table.................................................................357
Data Type or Domain.......................................................................358
Data Type........................................................................................358
Predefined Type...............................................................................358
Digit................................................................................................. 359
Expression.......................................................................................359
Factor............................................................................................... 359
Grouping element............................................................................359
Hex.................................................................................................. 359
Index Column................................................................................... 360
Insert values....................................................................................360
Interval qualifier............................................................................... 360
Join specification..............................................................................360
Merge when clause..........................................................................361
Merge when matched clause............................................................361
Merge when not matched clause.....................................................361
Name............................................................................................... 361
Operand........................................................................................... 362
Override clause................................................................................ 362
Query............................................................................................... 363
Quoted Name................................................................................... 363
Referential Constraint......................................................................364
References Specification..................................................................364
Referential Action............................................................................364
Script Compression Encryption........................................................365
Select order.....................................................................................365
21 of 428
Row value expression......................................................................365
Select Expression............................................................................. 366
Sequence value expression..............................................................366
Sequence option..............................................................................366
Alter sequence option......................................................................367
Alter identity column option.............................................................367
Basic sequence option.....................................................................368
Set clause list................................................................................... 369
Sort specification.............................................................................369
Sort specification list........................................................................ 369
Summand........................................................................................369
Table Expression.............................................................................. 370
Within group specification................................................................370
Wildcard expression......................................................................... 370
Window name or specification.........................................................371
Window specification.......................................................................371
Window frame.................................................................................. 371
Window frame preceding.................................................................372
Window frame bound.......................................................................373
Term................................................................................................ 373
Time zone........................................................................................ 374
Column............................................................................................ 374
System Tables........................................................................................ 375
Index................................................................................................... 375
Information Schema............................................................................ 376
CHECK_CONSTRAINTS......................................................................376
COLLATIONS..................................................................................... 376
COLUMNS......................................................................................... 377
COLUMN_PRIVILEGES.......................................................................380
CONSTANTS.....................................................................................381
CONSTRAINT_COLUMN_USAGE.........................................................383
DOMAINS.........................................................................................384
DOMAIN_CONSTRAINTS....................................................................386
ELEMENT_TYPES............................................................................... 387
ENUM_VALUES.................................................................................389
FIELDS.............................................................................................. 389
INDEXES........................................................................................... 391
INDEX_COLUMNS.............................................................................392
INFORMATION_SCHEMA_CATALOG_NAME........................................393
IN_DOUBT........................................................................................393
KEY_COLUMN_USAGE.......................................................................394
LOCKS.............................................................................................. 394
PARAMETERS...................................................................................395
QUERY_STATISTICS..........................................................................397
22 of 428
REFERENTIAL_CONSTRAINTS............................................................398
RIGHTS............................................................................................. 399
ROLES.............................................................................................. 399
ROUTINES........................................................................................ 399
SCHEMATA....................................................................................... 402
SEQUENCES.....................................................................................403
SESSIONS......................................................................................... 404
SESSION_STATE...............................................................................405
SETTINGS......................................................................................... 405
SYNONYMS....................................................................................... 406
TABLES............................................................................................. 406
TABLE_CONSTRAINTS.......................................................................407
TABLE_PRIVILEGES...........................................................................408
TRIGGERS........................................................................................409
USERS.............................................................................................. 410
VIEWS.............................................................................................. 410
Range Table........................................................................................ 411
Build....................................................................................................... 413
Portability............................................................................................ 413
Environment........................................................................................ 413
Building the Software..........................................................................413
Using Apache Lucene.......................................................................414
Using Maven 2..................................................................................... 414
Using a Central Repository...............................................................414
Maven Plugin to Start and Stop the TCP Server................................414
Using Snapshot Version...................................................................415
Using Eclipse....................................................................................... 415
Translating.......................................................................................... 415
Submitting Source Code Changes.......................................................416
Reporting Problems or Requests.........................................................417
Automated Build.................................................................................418
Generating Railroad Diagrams............................................................418
History.................................................................................................... 419
Change Log......................................................................................... 419
History of this Database Engine..........................................................419
Why Java............................................................................................. 419
Supporters..........................................................................................420
Frequently Asked Questions...................................................................423
I Have a Problem or Feature Request...............................................423
Are there Known Bugs? When is the Next Release?.........................423
Is this Database Engine Open Source?.............................................424
Is Commercial Support Available?....................................................424
How to Create a New Database?......................................................424
How to Connect to a Database?.......................................................424
23 of 428
Where are the Database Files Stored?.............................................424
What is the Size Limit (Maximum Size) of a Database?....................425
Is it Reliable?.................................................................................... 425
Why is Opening my Database Slow?................................................426
My Query is Slow.............................................................................. 426
H2 is Very Slow................................................................................427
Column Names are Incorrect?..........................................................427
Float is Double?................................................................................ 427
How to Translate this Project?..........................................................427
How to Contribute to this Project?....................................................427
24 of 428
Quickstart
Embedding H2 in an Application
The H2 Console Application
Embedding H2 in an Application
This database can be used in embedded mode, or in server mode. To use
it in embedded mode, you need to:
• Add the h2*.jar to the classpath (H2 does not have any
dependencies)
• Use the JDBC driver class: org.h2.Driver
• The database URL jdbc:h2:~/test opens the database test in your
user home directory
• A new database is automatically created
If you don't have Windows XP, or if something does not work as expected,
please see the detailed description in the Tutorial.
Step-by-Step
Installation
Install the software using the Windows Installer (if you did not yet do that).
25 of 428
Start the Console
Click [Start], [All Programs], [H2], and [H2 Console (Command Line)]:
Also, a new browser page should open with the URL http://localhost:8082.
You may get a security warning from the firewall. If you don't want other
computers in the network to access the database on your machine, you
can let the firewall block these connections. Only local connections are
required at this time.
Login
Select [Generic H2] and click [Connect]:
26 of 428
Sample
Click on the [Sample SQL Script]:
27 of 428
Execute
Click [Run]
On the left side, a new entry TEST is added below the database icon. The
28 of 428
operations and results of the statements are shown below the script.
Disconnect
Click on [Disconnect]:
End
Close the console window. For more information, see the Tutorial.
29 of 428
Installation
Requirements
Supported Platforms
Installing the Software
Directory Structure
Requirements
To run this database, the following software stack is known to work. Other
software most likely also works, but is not tested as much.
Database Engine
• Windows XP or Vista, Mac OS X, or Linux
• Oracle Java 8 or newer
• Recommended Windows file system: NTFS (FAT32 only supports files
up to 4 GB)
H2 Console
• Mozilla Firefox
Supported Platforms
As this database is written in Java, it can run on many different platforms.
It is tested with Java 8 and 11. All major operating systems (Windows, Mac
OS X, Linux, ...) are supported.
Directory Structure
After installing, you should get the following directory structure:
Directory Contents
bin JAR and batch files
docs Documentation
docs/html HTML pages
30 of 428
docs/javadoc Javadoc files
ext External dependencies (downloaded when building)
service Tools to run the database as a Windows Service
src Source files
src/docsrc Documentation sources
src/installer Installer, shell, and release build script
src/main Database engine source code
src/test Test source code
src/tools Tools and database adapters source code
31 of 428
Tutorial
Starting and Using the H2 Console
Special H2 Console Syntax
Settings of the H2 Console
Connecting to a Database using JDBC
Creating New Databases
Using the Server
Using Hibernate
Using TopLink and Glassfish
Using EclipseLink
Using Apache ActiveMQ
Using H2 within NetBeans
Using H2 with jOOQ
Using Databases in Web Applications
CSV (Comma Separated Values) Support
Upgrade, Backup, and Restore
Command Line Tools
The Shell Tool
Using OpenOffice Base
Java Web Start / JNLP
Using a Connection Pool
Fulltext Search
User-Defined Variables
Date and Time
Using Spring
OSGi
Java Management Extension (JMX)
32 of 428
This is a client/server application, so both a server and a client (a browser)
are required to run it.
Depending on your platform and environment, there are multiple ways to
start the H2 Console:
OS Start
Click [Start], [All Programs], [H2], and [H2 Console (Command
Line)]
An icon will be added to the system tray:
Windows If you don't get the window and the system tray icon, then
maybe Java is not installed correctly (in this case, try another
way to start the application). A browser window should open
and point to the login page at http://localhost:8082.
Open a file browser, navigate to h2/bin, and double click on
h2.bat.
Windows A console window appears. If there is a problem, you will see
an error message in this window. A browser window will open
and point to the login page (URL: http://localhost:8082).
Double click on the h2*.jar file. This only works if the .jar suffix
Any
is associated with Java.
Open a console window, navigate to the directory h2/bin, and
type:
Any
java -jar h2*.jar
33 of 428
Firewall
If you start the server, you may get a security warning from the firewall (if
you have installed one). If you don't want other computers in the network
to access the application on your machine, you can let the firewall block
those connections. The connection from the local machine will still work.
Only if you want other computers to access the database on this
computer, you need allow remote connections in the firewall.
It has been reported that when using Kaspersky 7.0 with firewall, the H2
Console is very slow when connecting over the IP address. A workaround
is to connect using 'localhost'.
A small firewall is already built into the server: other computers may not
connect to the server by default. To change this, go to 'Preferences' and
select 'Allow connections from other computers'.
Testing Java
To find out which version of Java is installed, open a command prompt and
type:
java -version
If you get an error message, you may need to add the Java binary
directory to the path environment variable.
34 of 428
If no port is specified for the TCP and PG servers, each service will try to
listen on its default port. If the default port is already in use, a random
port is used.
Login
At the login page, you need to provide connection information to connect
to a database. Set the JDBC driver class of your database, the JDBC URL,
user name, and password. If you are done, click [Connect].
You can save and reuse previously saved settings. The settings are stored
in a properties file (see Settings of the H2 Console).
Error Messages
Error messages in are shown in red. You can show/hide the stack trace of
the exception by clicking on the message.
Command(s) Description
@autocommit_true;
Enable or disable autocommit.
@autocommit_false;
@cancel; Cancel the currently running statement.
@columns null null TEST; Call the corresponding
@index_info null null TEST; DatabaseMetaData.get method. Patterns are
@tables; case sensitive (usually identifiers are
@tables null null TEST; uppercase). For information about the
36 of 428
parameters, see the Javadoc documentation.
Missing parameters at the end of the line are
set to null. The complete list of metadata
commands is: @attributes,
@best_row_identifier, @catalogs, @columns,
@column_privileges, @cross_references,
@exported_keys, @imported_keys,
@index_info, @primary_keys, @procedures,
@procedure_columns, @pseudo_columns,
@schemas, @super_tables, @super_types,
@tables, @table_privileges, @table_types,
@type_info, @udts, @version_columns
@edit select * from test; Use an updatable result set.
@generated insert into test(
) values();
Show the result of
@generated(1) insert into te
Statement.getGeneratedKeys(). Names or
st() values();
one-based indexes of required columns can
@generated(ID,
be optionally specified.
"TIMESTAMP") insert into tes
t() values();
@history; List the command history.
Display the result of various Connection and
@info;
DatabaseMetaData methods.
Show the result set in list format (each
@list select * from test;
column on its own line, with row numbers).
Run the statement this many times.
Parameters (?) are set using a loop from 0 up
to x - 1. Random values are used for each
@loop 1000 select ?, ?/*rnd*/;
?/*rnd*/. A Statement object is used instead
@loop 1000 @statement
of a PreparedStatement if @statement is
select ?;
used. Result sets are read until
ResultSet.next() returns false. Timing
information is printed.
@maxrows 20; Set the maximum number of rows to display.
Show the used and free memory. This will
@memory;
call System.gc().
List the ResultSetMetaData after running the
@meta select 1;
query.
@parameter_meta select ?; Show the result of the
37 of 428
PreparedStatement.getParameterMetaData()
calls. The statement is not executed.
@prof_start;
Start/stop the built-in profiling tool. The top 3
call hash('SHA256', '', 10000
stack traces of the statement(s) between
00);
start and stop are listed (if there are 3).
@prof_stop;
Sleep for a number of seconds. Used to
@prof_start;
profile a long running query or operation that
@sleep 10;
is running in another session (but in the
@prof_stop;
same process).
Display (without parameters) or change (with
@transaction_isolation;
parameters 1, 2, 4, 8) the transaction
@transaction_isolation 2;
isolation level.
import java.sql.*;
38 of 428
public class Test {
public static void main(String[] a)
throws Exception {
Connection conn = DriverManager.
getConnection("jdbc:h2:~/test", "sa", "");
// add application code here
conn.close();
}
}
Welcome to H2 Shell
Exit with Ctrl+C
[Enter] jdbc:h2:mem:2
URL jdbc:h2:./path/to/database
[Enter] org.h2.Driver
Driver
39 of 428
[Enter] sa
User your_username
Password (hidden)
Type the same password again to confirm database creation.
Password (hidden)
Connected
sql> quit
Connection closed
40 of 428
Starting the Server Tool from Command Line
To start the Server tool from the command line with the default settings,
run:
This will start the tool with the default options. To get the list of options
and default values, run:
There are options available to use other ports, and start or not start parts.
import org.h2.tools.Server;
...
// start the TCP Server
Server server = Server.createTcpServer(args).start();
...
// stop the TCP Server
server.stop();
41 of 428
password
To stop the server from a user application, use the following code:
org.h2.tools.Server.shutdownTcpServer("tcp://localhost:9092",
"password", false, false);
This function will only stop the TCP server. If other server were started in
the same process, they will continue to run. To avoid recovery when the
databases are opened the next time, all connections to the databases
should be closed before calling this method. To stop a remote server,
remote connections must be enabled on the server. Shutting down a TCP
server is protected using the option -tcpPassword (the same password
must be used to start and stop the TCP server).
Using Hibernate
This database supports Hibernate version 3.1 and newer. You can use the
HSQLDB Dialect, or the native H2 Dialect.
When using Hibernate, try to use the H2Dialect if possible. When using the
H2Dialect, compatibility modes such as MODE=MySQL are not supported.
When using such a compatibility mode, use the Hibernate dialect for the
corresponding database instead of the H2Dialect; but please note H2 does
not support all features of all databases.
<property
42 of 428
name="toplink.target-database"
value="oracle.toplink.essentials.platform.database.H2Platform"/>
Using EclipseLink
To use H2 in EclipseLink, use the platform class
org.eclipse.persistence.platform.database.H2Platform. If this platform is
not available in your version of EclipseLink, you can use the
OraclePlatform instead in many case. See also H2Platform.
43 of 428
Using H2 with jOOQ
jOOQ adds a thin layer on top of JDBC, allowing for type-safe SQL
construction, including advanced SQL, stored procedures and advanced
data types. jOOQ takes your database schema as a base for code
generation. If this is your example schema:
then run the jOOQ code generator on the command line using this
command:
Using the generated source, you can query the database as follows:
Embedded Mode
The (currently) simplest solution is to use the database in the embedded
mode, that means open a connection in your application when it starts (a
good solution is using a Servlet Listener, see below), or when a session
starts. A database can be accessed from multiple sessions and
applications at the same time, as long as they run in the same process.
Most Servlet Containers (for example Tomcat) are just using one process,
so this is not a problem (unless you run Tomcat in clustered mode).
Tomcat uses multiple threads and multiple classloaders. If multiple
applications access the same database at the same time, you need to put
the database jar in the shared/lib or server/lib directory. It is a good idea
to open the database when the web application starts, and close it when
the web application stops. If using multiple applications, only one (any) of
them needs to do that. In the application, an idea is to use one connection
per Session, or even one connection per request (action). Those
connections should be closed after use if possible (but it's not that bad if
they don't get closed).
Server Mode
The server mode is similar, but it allows you to run the server in another
process.
<listener>
<listener-class>org.h2.server.web.DbStarter</listener-class>
45 of 428
</listener>
<listener>
<listener-class>org.h2.server.web.JakartaDbStarter</listener-class>
</listener>
For details on how to access the database, see the file DbStarter.java. By
default this tool opens an embedded connection using the database URL
jdbc:h2:~/test, user name sa, and password sa. If you want to use this
connection within your servlet, you can access as follows:
DbStarter can also start the TCP server, however this is disabled by
default. To enable it, use the parameter db.tcpServer in the file web.xml.
Here is the complete list of options. These options need to be placed
between the description tag and the listener / filter tags:
<context-param>
<param-name>db.url</param-name>
<param-value>jdbc:h2:~/test</param-value>
</context-param>
<context-param>
<param-name>db.user</param-name>
<param-value>sa</param-value>
</context-param>
<context-param>
<param-name>db.password</param-name>
<param-value>sa</param-value>
</context-param>
<context-param>
<param-name>db.tcpServer</param-name>
<param-value>-tcpAllowOthers</param-value>
</context-param>
46 of 428
Using the H2 Console Servlet
The H2 Console is a standalone application and includes its own web
server, but it can be used as a servlet as well. To do that, include the
h2*.jar file in your application, and add the following configuration to your
web.xml:
<servlet>
<servlet-name>H2Console</servlet-name>
<servlet-class>org.h2.server.web.WebServlet</servlet-class>
<!--
<init-param>
<param-name>webAllowOthers</param-name>
<param-value></param-value>
</init-param>
<init-param>
<param-name>trace</param-name>
<param-value></param-value>
</init-param>
-->
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>H2Console</servlet-name>
<url-pattern>/console/*</url-pattern>
</servlet-mapping>
<!--
<security-role>
<role-name>admin</role-name>
</security-role>
<security-constraint>
<web-resource-collection>
<web-resource-name>H2 Console</web-resource-name>
<url-pattern>/console/*</url-pattern>
</web-resource-collection>
<auth-constraint>
<role-name>admin</role-name>
</auth-constraint>
</security-constraint>
-->
47 of 428
If your application is already Servlet 5-compatible, use the servlet class
org.h2.server.web.JakartaWebServlet instead.
To create a web application with just the H2 Console, run the following
command:
build warConsole
Please note for performance reason, CSVREAD should not be used inside a
join. Instead, import the data first (possibly into a temporary table), create
the required indexes if necessary, and then query this table.
48 of 428
Writing a CSV File from a Java Application
The Csv tool can be used in a Java application even when not using a
database at all. Example:
import java.sql.*;
import org.h2.tools.Csv;
import org.h2.tools.SimpleResultSet;
public class TestCsv {
public static void main(String[] args) throws Exception {
SimpleResultSet rs = new SimpleResultSet();
rs.addColumn("NAME", Types.VARCHAR, 255, 0);
rs.addColumn("EMAIL", Types.VARCHAR, 255, 0);
rs.addRow("Bob Meier", "[email protected]");
rs.addRow("John Jones", "[email protected]");
new Csv().write("data/test.csv", rs, null);
}
}
import java.sql.*;
import org.h2.tools.Csv;
public class TestCsv {
public static void main(String[] args) throws Exception {
ResultSet rs = new Csv().read("data/test.csv", null, null);
ResultSetMetaData meta = rs.getMetaData();
while (rs.next()) {
for (int i = 0; i < meta.getColumnCount(); i++) {
System.out.println(
meta.getColumnLabel(i + 1) + ": " +
rs.getString(i + 1));
}
System.out.println();
}
rs.close();
}
}
49 of 428
Upgrade, Backup, and Restore
Database Upgrade
The recommended way to upgrade from one version of the database
engine to the next version is to create a backup of the database (in the
form of a SQL script) using the old engine, and then execute the SQL
script using the new engine.
It is also possible to use the SQL command SCRIPT to create the backup of
the database. For more information about the options, see the SQL
command SCRIPT. The backup can be done remotely, however the file will
be created on the server side. The built in FTP server could be used to
retrieve the file from the server.
For more information about the options, see the SQL command
RUNSCRIPT. The restore can be done remotely, however the file needs to
be on the server side. The built in FTP server could be used to copy the file
to the server. It is also possible to use the SQL command RUNSCRIPT to
execute a SQL script. SQL script files may contain references to other
script files, in the form of RUNSCRIPT commands. However, when using
the server mode, the references script files need to be available on the
server side.
50 of 428
If the script was generated by H2 1.4.200 or an older version, add
VARIABLE_BINARY option to import it into more recent version.
Online Backup
The BACKUP SQL statement and the Backup tool both create a zip file with
the database file. However, the contents of this file are not human
readable.
The resulting backup is transactionally consistent, meaning the
consistency and atomicity rules apply.
BACKUP TO 'backup.zip'
You will be asked for a database URL, JDBC driver, user name, and
password. The connection setting can also be set as command line
parameters. After connecting, you will get the list of options. The built-in
commands don't need to end with a semicolon, but SQL statements are
only executed if the line ends with a semicolon ;. This allows to enter
multi-line statements:
By default, results are printed as a table. For results with many column,
consider using the list mode:
sql> list
Result list mode is now on
sql> select * from test;
ID : 1
NAME: Hello
ID : 2
NAME: World
(2 rows, 0 ms)
52 of 428
Using OpenOffice Base
OpenOffice.org Base supports database access over the JDBC API. To
connect to a H2 database using OpenOffice Base, you first need to add the
JDBC driver to OpenOffice. The steps to connect to a H2 database are:
• Start OpenOffice Writer, go to [Tools], [Options]
• Make sure you have selected a Java runtime environment in
OpenOffice.org / Java
• Click [Class Path...], [Add Archive...]
• Select your h2 jar file (location is up to you, could be wherever you
choose)
• Click [OK] (as much as needed), stop OpenOffice (including the
Quickstarter)
• Start OpenOffice Base
• Connect to an existing database; select [JDBC]; [Next]
• Example datasource URL: jdbc:h2:~/test
• JDBC driver class: org.h2.Driver
Now you can access the database stored in the current users home
directory.
To use H2 in NeoOffice (OpenOffice without X11):
• In NeoOffice, go to [NeoOffice], [Preferences]
• Look for the page under [NeoOffice], [Java]
• Click [Class Path], [Add Archive...]
• Select your h2 jar file (location is up to you, could be wherever you
choose)
• Click [OK] (as much as needed), restart NeoOffice.
Now, when creating a new database using the "Database Wizard" :
• Click [File], [New], [Database].
• Select [Connect to existing database] and the select [JDBC]. Click
next.
• Example datasource URL: jdbc:h2:~/test
• JDBC driver class: org.h2.Driver
Another solution to use H2 in NeoOffice is:
• Package the h2 jar within an extension package
• Install it as a Java extension in NeoOffice
53 of 428
This can be done by create it using the NetBeans OpenOffice plugin. See
also Extensions Development.
<security>
<all-permissions/>
</security>
import java.sql.*;
import org.h2.jdbcx.JdbcConnectionPool;
public class Test {
public static void main(String[] args) throws Exception {
JdbcConnectionPool cp = JdbcConnectionPool.create(
"jdbc:h2:~/test", "sa", "sa");
for (int i = 0; i < args.length; i++) {
Connection conn = cp.getConnection();
conn.createStatement().execute(args[i]);
conn.close();
}
cp.dispose();
}
}
54 of 428
Fulltext Search
H2 includes two fulltext search implementations. One is using Apache
Lucene, and the other (the native implementation) stores the index data
in special tables in the database.
You need to initialize it in each database where you want to use it.
Afterwards, you can create a fulltext index for a table using:
PUBLIC is the schema name, TEST is the table name. The list of column
names (comma separated) is optional, in this case all columns are
indexed. The index is updated in realtime. To search the index, use the
following query:
This will produce a result set that contains the query needed to retrieve
the data:
You need to initialize it in each database where you want to use it.
Afterwards, you can create a full text index for a table using:
PUBLIC is the schema name, TEST is the table name. The list of column
names (comma separated) is optional, in this case all columns are
indexed. The index is updated in realtime. To search the index, use the
following query:
This will produce a result set that contains the query needed to retrieve
the data:
To drop an index on a table (be warned that this will re-index all of the
full-text indices for the entire database):
56 of 428
name), COLUMNS (an array of column names), and KEYS (an array of
objects). To join a table, use a join as in: SELECT T.* FROM
FTL_SEARCH_DATA('Hello', 0, 0) FT, TEST T WHERE FT.TABLE='TEST' AND
T.ID=FT.KEYS[0];
You can also call the index from within a Java application:
User-Defined Variables
This database supports user-defined variables. Variables start with @ and
can be used wherever expressions or parameters are allowed. Variables
are not persisted and session scoped, that means only visible from within
the session in which they are defined. A value is usually assigned using
the SET command:
The value can also be changed using the SET() method. This is useful in
queries:
Variables that are not set evaluate to NULL. The data type of a user-
defined variable is the data type of the value assigned to it, that means it
is not necessary (or possible) to declare variable names before using
them. There are no restrictions on the assigned values; large objects
(LOBs) are supported as well. Rolling back a transaction does not affect
the value of a user-defined variable.
VALUES (
DATE '2008-01-01',
TIME '12:00:00',
TIME WITH TIME ZONE '12:00:00+01:00',
TIMESTAMP '2008-01-01 12:00:00',
TIMESTAMP WITH TIME ZONE '2008-01-01 12:00:00+01:00'
);
58 of 428
Using Spring
Using the TCP Server
Use the following configuration to start and stop the H2 TCP server using
the Spring Framework:
<bean id = "org.h2.tools.Server"
class="org.h2.tools.Server"
factory-method="createTcpServer"
init-method="start"
destroy-method="stop">
<constructor-arg value="-tcp,-tcpAllowOthers,-tcpPort,8043" />
</bean>
OSGi
The standard H2 jar can be dropped in as a bundle in an OSGi container.
H2 implements the JDBC Service defined in OSGi Service Platform Release
4 Version 4.2 Enterprise Specification. The H2 Data Source Factory service
is registered with the following properties:
OSGI_JDBC_DRIVER_CLASS=org.h2.Driver and
OSGI_JDBC_DRIVER_NAME=H2 JDBC Driver. The
OSGI_JDBC_DRIVER_VERSION property reflects the version of the driver as
is.
The following standard configuration properties are supported:
JDBC_USER, JDBC_PASSWORD, JDBC_DESCRIPTION,
JDBC_DATASOURCE_NAME, JDBC_NETWORK_PROTOCOL, JDBC_URL,
JDBC_SERVER_NAME, JDBC_PORT_NUMBER. Any other standard property
will be rejected. Non-standard properties will be passed on to H2 in the
connection URL.
59 of 428
the server mode, you need to connect to the server process). Then go to
the MBeans section. Under org.h2 you will find one entry per database.
The object name of the entry is the database short name, plus the path
(each colon is replaced with an underscore character).
The following attributes and operations are supported:
• CacheSize: the cache size currently in use in KB.
• CacheSizeMax (read/write): the maximum cache size in KB.
• Exclusive: whether this database is open in exclusive mode or not.
• FileReadCount: the number of file read operations since the database
was opened.
• FileSize: the file size in KB.
• FileWriteCount: the number of file write operations since the
database was opened.
• FileWriteCountTotal: the number of file write operations since the
database was created.
• LogMode (read/write): the current transaction log mode. See SET LOG
for details.
• Mode: the compatibility mode (REGULAR if no compatibility mode is
used).
• MultiThreaded: true if multi-threaded is enabled.
• Mvcc: true if MVCC is enabled.
• ReadOnly: true if the database is read-only.
• TraceLevel (read/write): the file trace level.
• Version: the database version in use.
• listSettings: list the database settings.
• listSessions: list the open sessions, including currently executing
statement (if any) and locked tables (if any).
To enable JMX, you may need to set the system properties
com.sun.management.jmxremote and
com.sun.management.jmxremote.port as required by the JVM.
60 of 428
Features
Feature List
H2 in Use
Connection Modes
Database URL Overview
Connecting to an Embedded (Local) Database
In-Memory Databases
Database Files Encryption
Database File Locking
Opening a Database Only if it Already Exists
Closing a Database
Ignore Unknown Settings
Changing Other Settings when Opening a Connection
Custom File Access Mode
Multiple Connections
Database File Layout
Logging and Recovery
Compatibility
Auto-Reconnect
Automatic Mixed Mode
Page Size
Using the Trace Options
Using Other Logging APIs
Read Only Databases
Read Only Databases in Zip or Jar File
Generated Columns (Computed Columns) / Function Based Index
Multi-Dimensional Indexes
User-Defined Functions and Stored Procedures
Pluggable or User-Defined Tables
Triggers
Compacting a Database
Cache Settings
External Authentication (Experimental)
61 of 428
Feature List
Main Features
• Very fast database engine
• Open source
• Written in Java
• Supports standard SQL, JDBC API
• Embedded and Server mode, Clustering support
• Strong security features
• The PostgreSQL ODBC driver can be used
• Multi version concurrency
Additional Features
• Disk based or in-memory databases and tables, read-only database
support, temporary tables
• Transaction support (read uncommitted, read committed, repeatable
read, snapshot), 2-phase-commit
• Multiple connections, row-level locking
• Cost based optimizer, using a genetic algorithm for complex queries,
zero-administration
• Scrollable and updatable result set support, large result set, external
result sorting, functions can return a result set
• Encrypted database (AES), SHA-256 password encryption, encryption
functions, SSL
SQL Support
• Support for multiple schemas, information schema
• Referential integrity / foreign key constraints with cascade, check
constraints
• Inner and outer joins, subqueries, read only views and inline views
• Triggers and Java functions / stored procedures
• Many built-in functions, including XML and lossless data compression
• Wide range of data types including large objects (BLOB/CLOB) and
arrays
• Sequences and identity columns, generated columns (can be used
for function based indexes)
• ORDER BY, GROUP BY, HAVING, UNION, OFFSET / FETCH (including
PERCENT and WITH TIES), LIMIT, TOP, DISTINCT / DISTINCT ON (...)
62 of 428
• Window functions
• Collation support, including support for the ICU4J library
• Support for users and roles
• Compatibility modes for IBM DB2, Apache Derby, HSQLDB, MS SQL
Server, MySQL, Oracle, and PostgreSQL.
Security Features
• Includes a solution for the SQL injection problem
• User password authentication uses SHA-256 and salt
• For server mode connections, user passwords are never transmitted
in plain text over the network (even when using insecure
connections; this only applies to the TCP server and not to the H2
Console however; it also doesn't apply if you set the password in the
database URL)
• All database files (including script files that can be used to backup
data) can be encrypted using the AES-128 encryption algorithm
• The remote JDBC driver supports TCP/IP connections over TLS
• The built-in web server supports connections over TLS
• Passwords can be sent to the database using char arrays instead of
Strings
H2 in Use
For a list of applications that work with or use H2, see: Links.
Connection Modes
The following connection modes are supported:
• Embedded mode (local connections using JDBC)
• Server mode (remote connections using JDBC or ODBC over TCP/IP)
• Mixed mode (local and remote connections at the same time)
Embedded Mode
In embedded mode, an application opens a database from within the
same JVM using JDBC. This is the fastest and easiest connection mode.
The disadvantage is that a database may only be open in one virtual
machine (and class loader) at any time. As in all modes, both persistent
and in-memory databases are supported. There is no limit on the number
of database open concurrently, or on the number of open connections.
In embedded mode I/O operations can be performed by application's
threads that execute a SQL command. The application may not interrupt
these threads, it can lead to database corruption, because JVM closes I/O
handle during thread interruption. Consider other ways to control
execution of your application. When interrupts are possible the async: file
system can be used as a workaround, but full safety is not guaranteed. It's
recommended to use the client-server model instead, the client side may
interrupt own threads.
64 of 428
Server Mode
When using the server mode (sometimes called remote mode or
client/server mode), an application opens a database remotely using the
JDBC or ODBC API. A server needs to be started within the same or
another virtual machine, or on another computer. Many applications can
connect to the same database at the same time, by connecting to this
server. Internally, the server process opens the database(s) in embedded
mode.
The server mode is slower than the embedded mode, because all data is
transferred over TCP/IP. As in all modes, both persistent and in-memory
databases are supported. There is no limit on the number of database
open concurrently per server, or on the number of open connections.
Mixed Mode
The mixed mode is a combination of the embedded and the server mode.
The first application that connects to a database does that in embedded
mode, but also starts a server so that other applications (running in
different processes or virtual machines) can concurrently access the same
data. The local connections are as fast as if the database is used in just
the embedded mode, while the remote connections are a bit slower.
The server can be started and stopped from within the application (using
the server API), or automatically (automatic mixed mode). When using the
automatic mixed mode, all clients that want to connect to the database
(no matter if it's an local or remote connection) can do so using the exact
same database URL.
65 of 428
Database URL Overview
This database supports multiple connection modes and connection
settings. This is achieved using different database URLs. Settings in the
URLs are not case sensitive.
67 of 428
Connecting to an Embedded (Local) Database
The database URL for connecting to a local database is jdbc:h2:[file:]
[<path>]<databaseName>. The prefix file: is optional. If no or only a
relative path is used, then the current working directory is used as a
starting point. The case sensitivity of the path and database name depend
on the operating system, however it is recommended to use lowercase
letters only. The database name must be at least three characters long (a
limitation of File.createTempFile). The database name must not contain a
semicolon. To point to the user home directory, use ~/, as in:
jdbc:h2:~/test.
In-Memory Databases
For certain use cases (for example: rapid prototyping, testing, high
performance operations, read-only databases), it may not be required to
persist data, or persist changes to the data. This database supports the in-
memory mode, where the data is not persisted.
In some cases, only one connection to a in-memory database is required.
This means the database to be opened is private. In this case, the
database URL is jdbc:h2:mem: Opening two connections within the same
virtual machine means opening two different (private) databases.
Sometimes multiple connections to the same in-memory database are
required. In this case, the database URL must include a name. Example:
jdbc:h2:mem:db1. Accessing the same database using this URL only works
within the same virtual machine and class loader environment.
To access an in-memory database from another process or from another
computer, you need to start a TCP server in the same process as the in-
memory database was created. The other processes then need to access
the database over TCP/IP or TLS, using a database URL such as:
jdbc:h2:tcp://localhost/mem:db1.
By default, closing the last connection to a database closes the database.
For an in-memory database, this means the content is lost. To keep the
database open, add ;DB_CLOSE_DELAY=-1 to the database URL. To keep
the content of an in-memory database as long as the virtual machine is
alive, use jdbc:h2:mem:test;DB_CLOSE_DELAY=-1. This may create a
memory leak, when you need to remove the database, use the
SHUTDOWN command.
68 of 428
Database Files Encryption
The database files can be encrypted. Three encryption algorithms are
supported:
• "AES" - also known as Rijndael, only AES-128 is implemented.
• "XTEA" - the 32 round version.
• "FOG" - pseudo-encryption only useful for hiding data from a text
editor.
To use file encryption, you need to specify the encryption algorithm (the
'cipher') and the file password (in addition to the user password) when
connecting to the database.
69 of 428
java -cp h2*.jar org.h2.tools.ChangeFileEncryption -dir ~ -db test -cipher
AES -encrypt filepwd
For more information about the algorithms, see Advanced / File Locking
Protocols.
Closing a Database
Delayed Database Closing
Usually, a database is closed when the last connection to it is closed. In
some situations this slows down the application, for example when it is
not possible to keep at least one connection open. The automatic closing
of a database can be delayed or disabled with the SQL statement SET
DB_CLOSE_DELAY <seconds>. The parameter <seconds> specifies the
number of seconds to keep a database open after the last connection to it
was closed. The following statement will keep a database open for 10
seconds after the last connection was closed:
SET DB_CLOSE_DELAY 10
The value -1 means the database is not closed automatically. The value 0
is the default and means the database is closed when the last connection
is closed. This setting is persistent and can be set by an administrator
only. It is possible to set the value in the database URL:
jdbc:h2:~/test;DB_CLOSE_DELAY=10.
71 of 428
Execute SQL on Connection
Sometimes, particularly for in-memory databases, it is useful to be able to
execute DDL or DML commands automatically when a client connects to a
database. This functionality is enabled via the INIT property. Note that
multiple commands may be passed to INIT, but the semicolon delimiter
must be escaped, as in the example below.
Multiple Connections
Opening Multiple Databases at the Same Time
An application can open multiple databases at the same time, including
multiple connections to the same database. The number of open database
is only limited by the memory available.
Multithreading Support
This database is multithreading-safe. If an application is multi-threaded, it
does not need to worry about synchronizing access to the database. An
application should normally use one connection per thread. This database
synchronizes access to the same connection, but other databases may not
do this. To get higher concurrency, you need to use multiple connections.
73 of 428
An application can use multiple threads that access the same database at
the same time. Threads that use different connections can use the
database concurrently.
74 of 428
File Name Description Number of Files
Database file.
Contains the transaction log,
test.mv.db 1 per database
indexes, and data for all tables.
Format: <database>.mv.db
Temporary file for database
compaction. 0 or 1 per
test.newFile
Contains the new MVStore file. database
Format: <database>.newFile
Temporary file for database
compaction.
0 or 1 per
test.tempFile Contains the temporary MVStore
database
file.
Format: <database>.tempFile
Database lock file.
Automatically (re-)created while the 1 per database
test.lock.db
database is in use. (only if in use)
Format: <database>.lock.db
Trace file (if the trace option is
enabled).
Contains trace information. 0 or 1 per
test.trace.db
Format: <database>.trace.db database
Renamed to
<database>.trace.db.old if too big.
Temporary file.
test.123.temp. Contains a temporary blob or a
1 per object
db large result set.
Format: <database>.<id>.temp.db
75 of 428
Backup
When the database is closed, it is possible to backup the database files.
To backup data while the database is running, the SQL commands SCRIPT
and BACKUP can be used.
Compatibility
All database engines behave a little bit different. Where possible, H2
supports the ANSI SQL standard, and tries to be compatible to other
databases. There are still a few differences however:
In MySQL text columns are case insensitive by default, while in H2 they
are case sensitive. However H2 supports case insensitive columns as well.
To create the tables with case insensitive texts, append
IGNORECASE=TRUE to the database URL (example:
jdbc:h2:~/test;IGNORECASE=TRUE).
Compatibility Modes
For certain features, this database can emulate the behavior of specific
databases. However, only a small subset of the differences between
databases are implemented in this way. Here is the list of currently
supported modes and the differences to the regular mode:
77 of 428
• MINUS can be used instead of EXCEPT.
• IDENTITY can be used as a data type.
• MS SQL Server-style IDENTITY clause is supported.
• Legacy SERIAL and BIGSERIAL data types are supported.
• AUTO_INCREMENT clause can be used instead of GENERATED
{ ALWAYS | BY DEFAULT } AS IDENTITY.
• If a value for identity column was specified in an INSERT command
the base value of sequence generator of this column is updated if
current value of generator was smaller (larger for generators with
negative increment) than the inserted value.
• Identity columns have implicit DEFAULT ON NULL clause. It means a
NULL value may be specified for this column in INSERT command and
it will be treated as DEFAULT.
• Oracle-style CURRVAL and NEXTVAL can be used on sequences.
• TOP clause can be used in DELETE and UPDATE.
• Non-standard Oracle-style WHERE clause can be used in standard
MERGE command.
• Attempt to reference a non-unique set of columns from a referential
constraint will create an UNIQUE constraint on them automatically.
• Unsafe comparison operators between numeric and boolean values
are allowed.
• IDENTITY() and SCOPE_IDENTITY() are supported, but both are
implemented like SCOPE_IDENTITY()
• SYSDATE, SYSTIMESTAMP, and TODAY are supported.
79 of 428
• For unique indexes, NULL is distinct. That means only one row with
NULL in one of the columns is allowed.
• Text can be concatenated using '+'.
• Arguments of LOG() function are swapped.
• MONEY data type is treated like NUMERIC(19, 4) data type.
SMALLMONEY data type is treated like NUMERIC(10, 4) data type.
• IDENTITY can be used for automatic id generation on column level.
• Table hints are discarded. Example: SELECT * FROM table WITH
(NOLOCK).
• Datetime value functions return the same value within a command.
• 0x literals are parsed as binary string literals.
• TRUNCATE TABLE restarts next values of generated columns.
• TOP clause in SELECT, UPDATE, and DELETE is supported.
• Unsafe comparison operators between numeric and boolean values
are allowed.
80 of 428
• Unrelated expressions in ORDER BY clause of DISTINCT queries are
allowed.
• Some MariaDB-specific ALTER TABLE commands are partially
supported.
• TRUNCATE TABLE restarts next values of generated columns.
• NEXT VALUE FOR returns different values when invoked multiple
times within the same row.
• If value of an identity column was manually specified, its sequence is
updated to generate values after inserted.
• NULL value works like DEFAULT value is assignments to identity
columns.
• LIMIT / OFFSET clauses are supported.
• AUTO_INCREMENT clause can be used.
• YEAR data type is treated like SMALLINT data type.
• GROUP BY clause can contain 1-based positions of expressions from
the SELECT list.
• Unsafe comparison operators between numeric and boolean values
are allowed.
Text comparison in MariaDB is case insensitive by default, while in H2 it is
case sensitive (as in most other databases). H2 does support case
insensitive text comparison, but it needs to be set separately, using SET
IGNORECASE TRUE. This affects comparison using =, LIKE, REGEXP.
81 of 428
• INSERT IGNORE is partially supported and may be used to skip rows
with duplicate keys if ON DUPLICATE KEY UPDATE is not specified.
• REPLACE INTO is partially supported.
• Spaces are trimmed from the right side of CHAR values.
• REGEXP_REPLACE() uses \ for back-references.
• Datetime value functions return the same value within a command.
• 0x literals are parsed as binary string literals.
• Unrelated expressions in ORDER BY clause of DISTINCT queries are
allowed.
• Some MySQL-specific ALTER TABLE commands are partially
supported.
• TRUNCATE TABLE restarts next values of generated columns.
• If value of an identity column was manually specified, its sequence is
updated to generate values after inserted.
• NULL value works like DEFAULT value is assignments to identity
columns.
• Referential constraints don't require an existing primary key or
unique constraint on referenced columns and create a unique
constraint automatically if such constraint doesn't exist.
• LIMIT / OFFSET clauses are supported.
• AUTO_INCREMENT clause can be used.
• YEAR data type is treated like SMALLINT data type.
• GROUP BY clause can contain 1-based positions of expressions from
the SELECT list.
• Unsafe comparison operators between numeric and boolean values
are allowed.
Text comparison in MySQL is case insensitive by default, while in H2 it is
case sensitive (as in most other databases). H2 does support case
insensitive text comparison, but it needs to be set separately, using SET
IGNORECASE TRUE. This affects comparison using =, LIKE, REGEXP.
82 of 428
• When using unique indexes, multiple rows with NULL in all columns
are allowed, however it is not allowed to have multiple rows with the
same values otherwise.
• Empty strings are treated like NULL values, concatenating NULL with
another value results in the other value.
• REGEXP_REPLACE() uses \ for back-references.
• RAWTOHEX() converts character strings to hexadecimal
representation of their UTF-8 encoding.
• HEXTORAW() decodes a hexadecimal character string to a binary
string.
• DATE data type is treated like TIMESTAMP(0) data type.
• Datetime value functions return the same value within a command.
• ALTER TABLE MODIFY COLUMN command is partially supported.
• SEQUENCE.NEXTVAL and SEQUENCE.CURRVAL are supported and
return values with DECIMAL/NUMERIC data type.
• Merge when matched clause may have WHERE clause.
• MINUS can be used instead of EXCEPT.
• SYSDATE and SYSTIMESTAMP are supported.
Auto-Reconnect
The auto-reconnect feature causes the JDBC driver to reconnect to the
database if the connection is lost. The automatic re-connect only occurs
when auto-commit is enabled; if auto-commit is disabled, an exception is
thrown. To enable this mode, append ;AUTO_RECONNECT=TRUE to the
database URL.
Re-connecting will open a new session. After an automatic re-connect,
variables and local temporary tables definitions (excluding data) are re-
created. The contents of the system table
INFORMATION_SCHEMA.SESSION_STATE contains all client side state that
is re-created.
If another connection uses the database in exclusive mode (enabled using
SET EXCLUSIVE 1 or SET EXCLUSIVE 2), then this connection will try to re-
connect until the exclusive mode ends.
jdbc:h2:/data/test;AUTO_SERVER=TRUE
84 of 428
Use the same URL for all connections to this database. Internally, when
using this mode, the first connection to the database is made in
embedded mode, and additionally a server is started internally (as a
daemon thread). If the database is already open in another process, the
server mode is used automatically. The IP address and port of the server
are stored in the file .lock.db, that's why in-memory databases can't be
supported.
The application that opens the first connection to the database uses the
embedded mode, which is faster than the server mode. Therefore the
main application should open the database first if possible. The first
connection automatically starts a server on a random port. This server
allows remote connections, however only to this database (to ensure that,
the client reads .lock.db file and sends the random key that is stored there
to the server). When the first connection is closed, the server stops. If
other (remote) connections are still open, one of them will then start a
server (auto-reconnect is enabled automatically).
All processes need to have access to the database files. If the first
connection is closed (the connection that started the server), open
transactions of other connections will be rolled back (this may not be a
problem if you don't disable autocommit). Explicit client/server
connections (using jdbc:h2:tcp:// or ssl://) are not supported. This mode is
not supported for in-memory databases.
Here is an example how to use this mode. Application 1 and 2 are not
necessarily started on the same computer, but they need to have access
to the database files. Application 1 and 2 are typically two different
processes (however they could run within the same process).
// Application 1:
DriverManager.getConnection("jdbc:h2:/data/test;AUTO_SERVER=TRUE");
// Application 2:
DriverManager.getConnection("jdbc:h2:/data/test;AUTO_SERVER=TRUE");
When using this feature, by default the server uses any free TCP port. The
port can be set manually using AUTO_SERVER_PORT=9090.
85 of 428
Page Size
The page size for new databases is 4 KiB (4096 bytes), unless the page
size is set explicitly in the database URL using PAGE_SIZE= when the
database is created. The page size of existing databases can not be
changed, so this property needs to be set when the database is created.
The page size of encrypted databases must be a multiple of 4096 (4096,
8192, …).
Trace Options
The simplest way to enable the trace option is setting it in the database
URL. There are two settings, one for System.out
(TRACE_LEVEL_SYSTEM_OUT) tracing, and one for file tracing
(TRACE_LEVEL_FILE). The trace levels are 0 for OFF, 1 for ERROR (the
default), 2 for INFO, and 3 for DEBUG. A database URL with both levels set
to DEBUG is:
jdbc:h2:~/test;TRACE_LEVEL_FILE=3;TRACE_LEVEL_SYSTEM_OUT=3
SET TRACE_LEVEL_SYSTEM_OUT 3
SET TRACE_MAX_FILE_SIZE 1
...
12-20 20:58:09 jdbc[0]:
/**/dbMeta3.getURL();
12-20 20:58:09 jdbc[0]:
/**/dbMeta3.getTables(null, "", null, new String[]{"BASE TABLE",
"VIEW"});
...
To filter the Java source code, use the ConvertTraceFile tool as follows:
The generated file Test.java will contain the Java source code. The
generated source code may be too large to compile (the size of a Java
method is limited). If this is the case, the source code needs to be split in
multiple methods. The password is not listed in the trace file and therefore
not included in the source code.
jdbc:h2:~/test;TRACE_LEVEL_FILE=4
Changing the log mechanism is not possible after the database is open,
that means executing the SQL statement SET TRACE_LEVEL_FILE 4 when
the database is already open will not have the desired effect. To use
SLF4J, all required jar files need to be in the classpath. The logger name is
h2database. If it does not work, check the file <database>.trace.db for
error messages.
jdbc:h2:zip:~/data.zip!/test
88 of 428
Databases in zip files are read-only. The performance for some queries will
be slower than when using a regular database, because random access in
zip files is not supported (only streaming). How much this affects the
performance depends on the queries and the data. The database is not
read in memory; therefore large databases are supported as well. The
same indexes are used as when using a regular database.
If the database is larger than a few megabytes, performance is much
better if the database file is split into multiple smaller files, because
random access in compressed files is not possible. See also the sample
application ReadOnlyDatabaseInZip.
Function indexes are not directly supported by this database, but they can
be emulated by using generated columns. For example, if an index on the
upper-case version of a column is required, create a generated column
with the upper-case version of the original column, and create an index for
this column:
When inserting data, it is not required (and not allowed) to specify a value
for the upper-case version of the column, because the value is generated.
But you can use the column when querying the table:
Multi-Dimensional Indexes
A tool is provided to execute efficient multi-dimension (spatial) range
queries. This database does not support a specialized spatial index (R-
Tree or similar). Instead, the B-Tree index is used. For each record, the
multi-dimensional key is converted (mapped) to a single dimensional
(scalar) value. This value specifies the location on a space-filling curve.
Currently, Z-order (also called N-order or Morton-order) is used; Hilbert
curve could also be used, but the implementation is more complex. The
algorithm to convert the multi-dimensional value is called bit-interleaving.
The scalar value is indexed using a B-Tree index (usually using a
generated column).
The method can result in a drastic performance improvement over just
using an index on the first column. Depending on the data and number of
dimensions, the improvement is usually higher than factor 5. The tool
generates a SQL query from a specified multi-dimensional range. The
method used is not database dependent, and the tool can easily be ported
to other databases. For an example how to use the tool, please have a
look at the sample code provided in TestMultiDimension.java.
90 of 428
a compiled class that is available in the classpath. By default, the function
aliases are stored in the current schema.
package acme;
import java.math.*;
public class Function {
public static boolean isPrime(int value) {
return new BigInteger(String.valueOf(value)).isProbablePrime(100);
}
}
package org.h2.dynamic;
< import statements before the tag @CODE; if not set:
import java.util.*;
import java.math.*;
import java.sql.*;
>
public class <aliasName> {
public static <sourceCode>
}
Method Overloading
Multiple methods may be bound to a SQL function if the class is already
compiled and included in the classpath. Each Java method must have a
different number of arguments. Method overloading is not supported
when declaring functions as source code.
Using SimpleResultSet
A function can create a result set using the SimpleResultSet tool:
import org.h2.tools.SimpleResultSet;
...
public static ResultSet simpleResultSet() throws SQLException {
SimpleResultSet rs = new SimpleResultSet();
rs.addColumn("ID", Types.INTEGER, 10, 0);
rs.addColumn("NAME", Types.VARCHAR, 255, 0);
93 of 428
rs.addRow(0, "Hello");
rs.addRow(1, "World");
return rs;
}
94 of 428
Pluggable or User-Defined Tables
For situations where you need to expose other data-sources to the SQL
engine as a table, there are "pluggable tables". For some examples, have
a look at the code in org.h2.test.db.TestTableEngines.
In order to create your own TableEngine, you need to implement the
org.h2.api.TableEngine interface e.g. something like this:
package acme;
public static class MyTableEngine implements org.h2.api.TableEngine {
Params from the schema are used when CREATE TABLE issued on this
schema does not have its own engine params specified.
95 of 428
Triggers
This database supports Java triggers that are called before or after a row
is updated, inserted or deleted. Triggers can be used for complex
consistency checks, or to update related data in the database. It is also
possible to use triggers to simulate materialized views. For a complete
sample application, see src/test/org/h2/samples/TriggerSample.java. A
Java trigger must implement the interface org.h2.api.Trigger. The trigger
class must be available in the classpath of the database engine (when
using the server mode, it must be in the classpath of the server).
import org.h2.api.Trigger;
...
public class TriggerSample implements Trigger {
The connection can be used to query or update data in other tables. The
trigger then needs to be defined in the database:
96 of 428
The trigger can be used to veto a change by throwing a SQLException.
As an alternative to implementing the Trigger interface, an application can
extend the abstract class org.h2.tools.TriggerAdapter. This will allows to
use the ResultSet interface within trigger implementations. In this case,
only the fire method needs to be implemented:
import org.h2.tools.TriggerAdapter;
...
public class TriggerSample extends TriggerAdapter {
Compacting a Database
Empty space in the database file re-used automatically. When closing the
database, the database is automatically compacted for up to 200
milliseconds by default. To compact more, use the SQL statement
SHUTDOWN COMPACT. However re-creating the database may further
reduce the database size because this will re-build the indexes. Here is a
sample function to do this:
97 of 428
Cache Settings
The database keeps most frequently used data in the main memory. The
amount of memory used for caching can be changed using the setting
CACHE_SIZE. This setting can be set in the database connection URL
(jdbc:h2:~/test;CACHE_SIZE=131072), or it can be changed at runtime
using SET CACHE_SIZE size. The size of the cache, as represented by
CACHE_SIZE is measured in KB, with each KB being 1024 bytes. This
setting has no effect for in-memory databases. For persistent databases,
the setting is stored in the database and re-used when the database is
opened the next time. However, when opening an existing database, the
cache size is set to at most half the amount of memory available for the
virtual machine (Runtime.getRuntime().maxMemory()), even if the cache
size setting stored in the database is larger; however the setting stored in
the database is kept. Setting the cache size in the database URL or
explicitly using SET CACHE_SIZE overrides this value (even if larger than
the physical memory). To get the current used maximum cache size, use
the query SELECT * FROM INFORMATION_SCHEMA.SETTINGS WHERE
SETTING_NAME = 'info.CACHE_MAX_SIZE'
An experimental scan-resistant cache algorithm "Two Queue" (2Q) is
available. To enable it, append ;CACHE_TYPE=TQ to the database URL.
The cache might not actually improve performance. If you plan to use it,
please run your own test cases first.
Also included is an experimental second level soft reference cache. Rows
in this cache are only garbage collected on low memory. By default the
second level cache is disabled. To enable it, use the prefix SOFT_.
Example: jdbc:h2:~/test;CACHE_TYPE=SOFT_LRU. The cache might not
actually improve performance. If you plan to use it, please run your own
test cases first.
To get information about page reads and writes, and the current caching
algorithm in use, call SELECT * FROM INFORMATION_SCHEMA.SETTINGS.
The number of pages read / written is listed.
98 of 428
assign roles to externally authenticated users. This feature is
experimental and subject to change
Master user cannot be externally authenticated
To enable external authentication on a database execute statement SET
AUTHENTICATOR TRUE. This setting in persisted on the database.
To connect on a database by using external credentials client must
append AUTHREALM=H2 to the database URL. H2 is the identifier of the
authentication realm (see later).
External authentication requires to send password to the server. For this
reason is works only on local connection or remote over ssl
By default external authentication is performed through JAAS login
interface (configuration name is h2). To configure JAAS add argument -
Djava.security.auth.login.config=jaas.conf Here an example of JAAS login
configuration file content:
h2 {
com.sun.security.auth.module.LdapLoginModule REQUIRED \
userProvider="ldap://127.0.0.1:10389"
authIdentity="uid={USERNAME},ou=people,dc=example,dc=com" \
debug=true useSSL=false ;
};
validatorClass="org.h2.security.auth.impl.FixedPasswordCredentialsValid
ator">
<property name="userNamePattern" value="DUMMY[0-9]" />
<property name="password" value="mock" />
</realm>
99 of 428
<realm name="LDAPEXAMPLE"
validatorClass="org.h2.security.auth.impl.LdapCredentialsValidator">
<property name="bindDnPattern" value="uid=
%u,ou=people,dc=example,dc=com" />
<property name="host" value="127.0.0.1" />
<property name="port" value="10389" />
<property name="secure" value="false" />
</realm>
<!-- realm JAAS: perform credentials validation by using JAAS api -->
<realm name="JAAS"
validatorClass="org.h2.security.auth.impl.JaasCredentialsValidator">
<property name="appName" value="H2" />
</realm>
100 of 428
Securing your H2
Introduction
Network exposed
Alias / Stored Procedures
Grants / Roles / Permissions
Encrypted storage
Introduction
H2 is __not__ designed to be run in an adversarial environment. You
should absolutely not expose your H2 server to untrusted connections.
Running H2 in embedded mode is the best choice - it is not externally
exposed.
Network exposed
When running an H2 server in TCP mode, first prize is to run with it only
listening to connections on localhost (i.e 127.0.0.1).
Second prize is running listening to restricted ports on a secured network.
If you expose H2 to the broader Internet, you can secure the connection
with SSL, but this is a rather tricky thing to get right, between JVM bugs,
certificates and choosing a decent cipher.
Encrypted storage
Encrypting your on-disk database will provide a small measure of security
to your stored data. You should not assume that this is any kind of real
security against a determined opponent however, since there are many
101 of 428
repeated data structures that will allow someone with resources and time
to extract the secret key.
Also the secret key is visible to anything that can read the memory of the
process.
102 of 428
Performance
Performance Comparison
PolePosition Benchmark
Database Performance Tuning
Using the Built-In Profiler
Application Profiling
Database Profiling
Statement Execution Plans
How Data is Stored and How Indexes Work
Fast Database Import
Performance Comparison
In many cases H2 is faster than other (open source and not open source)
database engines. Please note this is mostly a single connection
benchmark run on one computer, with many very simple operations
running against the database. This benchmark does not include very
complex queries. The embedded mode of H2 is faster than the client-
server mode because the per-statement overhead is greatly reduced.
Embedded
Test Case Unit H2 HSQLDB Derby
Simple: Init ms 1021 2510 6762
Simple: Query (random) ms 513 653 2035
Simple: Query (sequential) ms 1344 2210 7665
Simple: Update (sequential) ms 1642 3040 7034
Simple: Delete (sequential) ms 1697 2310 9981
Simple: Memory Usage MB 18 15 13
BenchA: Init ms 801 2877 6576
BenchA: Transactions ms 1369 2629 4987
BenchA: Memory Usage MB 12 15 9
BenchB: Init ms 966 2544 7161
BenchB: Transactions ms 341 2316 815
103 of 428
BenchB: Memory Usage MB 14 10 10
BenchC: Init ms 2630 3144 7420
BenchC: Transactions ms 1732 1742 2735
BenchC: Memory Usage MB 19 34 11
Executed statements # 2222032 2222032 2222032
Total time ms 14056 25975 63171
Statements per second #/s 158084 85545 35174
Client-Server
Test Case Unit H2 HSQLDB Derby PostgreSQL MySQL
Simple: Init ms 27989 48055 47142 32972 109482
Simple:
Query ms 4821 5984 14741 4089 15140
(random)
Simple:
Query ms 33656 49112 95999 35676 143536
(sequential)
Simple:
Update ms 9878 23565 31418 26113 50676
(sequential)
Simple:
Delete ms 13056 28584 43955 20985 64647
(sequential)
Simple:
Memory MB 18 15 15 2 4
Usage
BenchA: Init ms 20993 42525 38335 27794 107723
BenchA:
Transaction ms 16549 29255 28995 23113 65036
s
BenchA:
Memory MB 12 18 11 1 4
Usage
BenchB: Init ms 26785 48772 39756 32369 115398
BenchB: ms 898 10046 1916 818 1794
104 of 428
Transaction
s
BenchB:
Memory MB 16 11 12 2 5
Usage
BenchC:
ms 18266 26865 39325 24547 70531
Init
BenchC:
Transaction ms 6569 7783 9412 8916 19150
s
BenchC:
Memory MB 17 35 13 2 7
Usage
Executed
# 2222032 2222032 2222032 2222032 2222032
statements
Total time ms 179460 320546 390994 237392 763113
Statements
#/s 12381 6932 5683 9360 2911
per second
HSQLDB
Version 2.5.1 was used for the test. Cached tables are used in this test
(hsqldb.default_table_type=cached), and the write delay is 1 second (SET
WRITE_DELAY 1).
Derby
Version 10.14.2.0 was used for the test. Derby is clearly the slowest
embedded database in this test. This seems to be a structural problem,
because all operations are really slow. It will be hard for the developers of
Derby to improve the performance to a reasonable level. A few problems
105 of 428
have been identified: leaving autocommit on is a problem for Derby. If it is
switched off during the whole test, the results are about 20% better for
Derby. Derby calls FileChannel.force(false), but only twice per log file (not
on each commit). Disabling this call improves performance for Derby by
about 2%. Unlike H2, Derby does not call FileDescriptor.sync() on each
checkpoint. Derby supports a testing mode (system property
derby.system.durability=test) where durability is disabled. According to
the documentation, this setting should be used for testing only, as the
database may not recover after a crash. Enabling this setting improves
performance by a factor of 2.6 (embedded mode) or 1.4 (server mode).
Even if enabled, Derby is still less than half as fast as H2 in default mode.
PostgreSQL
Version 13.4 was used for the test. The following options where changed
in postgresql.conf: fsync = off, commit_delay = 100000 (microseconds).
PostgreSQL is run in server mode. The memory usage number is incorrect,
because only the memory usage of the JDBC driver is measured.
MySQL
Version 8.0.27 was used for the test. MySQL was run with the InnoDB
backend. The setting innodb_flush_log_at_trx_commit and
sync_binlogcode> (found in the my.ini / community-mysql-server.cnf file)
was set to 0. Otherwise (and by default), MySQL is slow (around 140
statements per second in this test) because it tries to flush the data to
disk for each commit. For small transactions (when autocommit is on) this
is really slow. But many use cases use small or relatively small
transactions. Too bad this setting is not listed in the configuration wizard,
and it always overwritten when using the wizard. You need to change
those settings manually in the file my.ini / community-mysql-server.cnf,
and then restart the service. The memory usage number is incorrect,
because only the memory usage of the JDBC driver is measured.
SQLite
SQLite 3.36.0.3, configured to use WAL and with synchronous=NORMAL
was tested in a separate, less reliable run. A rough estimate is that SQLite
performs approximately 2-5x worse in the simple benchmarks, which
perform simple work in the database, resulting in a low work-per-
transaction ratio. SQLite becomes competitive as the complexity of the
106 of 428
database interactions increases. The results seemed to vary drastically
across machine, and more reliable results should be obtained. Benchmark
on your production hardware.
The benchmarks used include multi-threaded scenarios, and we were not
able to get the SQLite JDBC driver we used to work with them. Help with
configuring the driver for multi-threaded usage is welcome.
Firebird
Firebird 3.0 (default installation) was tested, but failed on multi-threaded
part of the test. It is likely possible to run the performance test with the
Firebird database, and any information on how to configure Firebird for
this are welcome.
build benchmark
Number of Connections
This is mostly a single-connection benchmark. BenchB uses multiple
connections; the other tests use one connection.
Real-World Tests
Good benchmarks emulate real-world use cases. This benchmark includes
4 test cases: BenchSimple uses one table and many small updates /
deletes. BenchA is similar to the TPC-A test, but single connection / single
threaded (see also: www.tpc.org). BenchB is similar to the TPC-B test,
107 of 428
using multiple connections (one thread per connection). BenchC is similar
to the TPC-C test, but single connection / single threaded.
Test Platform
This test is run on Fedora v.34 with Oracle JVM 1.8 and SSD drive.
Multiple Runs
When a Java benchmark is run first, the code is not fully compiled and
therefore runs slower than when running multiple times. A benchmark
should always run the same test multiple times and ignore the first run(s).
This benchmark runs three times, but only the last run is measured.
Memory Usage
It is not enough to measure the time taken, the memory usage is
important as well. Performance can be improved by using a bigger cache,
but the amount of memory is limited. HSQLDB tables are kept fully in
memory by default; this benchmark uses 'disk based' tables for all
databases. Unfortunately, it is not so easy to calculate the memory usage
of PostgreSQL and MySQL, because they run in a different process than
the test. This benchmark currently does not print memory usage of those
databases.
Delayed Operations
Some databases delay some operations (for example flushing the buffers)
until after the benchmark is run. This benchmark waits between each
database tested, and each database runs in a different process
(sequentially).
PolePosition Benchmark
The PolePosition is an open source benchmark. The algorithms are all
quite simple. It was developed / sponsored by db4o. This test was not run
for a longer time, so please be aware that the results below are for older
database versions (H2 version 1.1, HSQLDB 1.8, Java 1.4).
109 of 428
Bahrain write ms 1186 1387 6904
Bahrain query_indexed_string ms 336 170 693
Bahrain query_string ms 18064 39703 41243
Bahrain query_indexed_int ms 104 134 678
Bahrain update ms 191 87 159
Bahrain delete ms 1215 729 6812
Imola retrieve ms 198 194 4036
Barcelona write ms 413 832 3191
Barcelona read ms 119 160 1177
Barcelona query ms 20 5169 101
Barcelona delete ms 388 319 3287
Total ms 26724 53962 87112
There are a few problems with the PolePosition test:
• HSQLDB uses in-memory tables by default while H2 uses persistent
tables. The HSQLDB version included in PolePosition does not support
changing this, so you need to replace poleposition-0.20/lib/hsqldb.jar
with a newer version (for example hsqldb-1.8.0.7.jar), and then use
the setting
hsqldb.connecturl=jdbc:hsqldb:file:data/hsqldb/dbbench2;hsqldb.def
ault_table_type=cached;sql.enforce_size=true in the file
Jdbc.properties.
• HSQLDB keeps the database open between tests, while H2 closes the
database (losing all the cache). To change that, use the database
URL jdbc:h2:file:data/h2/dbbench;DB_CLOSE_DELAY=-1
• The amount of cache memory is quite important, specially for the
PolePosition test. Unfortunately, the PolePosition test does not take
this into account.
110 of 428
database is closed. By default the database is closed if the last connection
is closed.
If you open and close connections a lot but don't want to use a connection
pool, consider keeping a 'sentinel' connection open for as long as the
application runs, or use delayed database closing. See also Closing a
database.
Virus Scanners
Some virus scanners scan files every time they are accessed. It is very
important for performance that database files are not scanned for viruses.
The database engine never interprets the data stored in the files as
programs, that means even if somebody would store a virus in a database
file, this would be harmless (when the virus does not run, it cannot
spread). Some virus scanners allow to exclude files by suffix. Ensure files
ending with .db are not scanned.
Index Usage
This database uses indexes to improve the performance of SELECT,
UPDATE, DELETE. If a column is used in the WHERE clause of a query, and
if an index exists on this column, then the index can be used. Multi-
column indexes are used if all or the first columns of the index are used.
Both equality lookup and range scans are supported. Indexes are used to
order result sets, but only if the condition uses the same index or no index
111 of 428
at all. The results are sorted in memory if required. Indexes are created
automatically for primary key and unique constraints. Indexes are also
created for foreign key constraints, if required. For other columns, indexes
need to be created manually using the CREATE INDEX statement.
Index Hints
If you have determined that H2 is not using the optimal index for your
query, you can use index hints to force H2 to use specific indexes.
Only indexes in the list will be used when choosing an index to use on the
given table. There is no significance to order in this list.
It is possible that no index in the list is chosen, in which case a full table
scan will be used.
An empty list of index names forces a full table scan to be performed.
Each index in the list must exist.
112 of 428
For each additional index, one new "index b-tree" is created. The key of
this b-tree consists of the indexed columns, plus the key of the data b-
tree. If a primary key is created after the table has been created, or if the
primary key contains multiple column, or if the primary key is not of the
data types listed above, then the primary key is stored in a new index b-
tree.
Optimizer
This database uses a cost based optimizer. For simple and queries and
queries with medium complexity (less than 7 tables in the join), the
expected cost (running time) of all possible plans is calculated, and the
plan with the lowest cost is used. For more complex queries, the algorithm
first tries all possible combinations for the first few tables, and the
remaining tables added using a greedy algorithm (this works well for most
joins). Afterwards a genetic algorithm is used to test at most 2000 distinct
plans. Only left-deep plans are evaluated.
Expression Optimization
After the statement is parsed, all expressions are simplified automatically
if possible. Operations are evaluated only once if all parameters are
constant. Functions are also optimized, but only if the function is constant
(always returns the same result for the same parameter values). If the
WHERE clause is always false, then the table is not accessed at all.
COUNT(*) Optimization
If the query only counts all rows of a table, then the data is not accessed.
However, this is only possible if no WHERE clause is used, that means it
only works for queries of the form SELECT COUNT(*) FROM table.
113 of 428
If a table has multiple indexes, sometimes more than one index could be
used. Example: if there is a table TEST(ID, NAME, FIRSTNAME) and an
index on each column, then two indexes could be used for the query
SELECT * FROM TEST WHERE NAME='A' AND FIRSTNAME='B', the index on
NAME or the index on FIRSTNAME. It is not possible to use both indexes at
the same time. Which index is used depends on the selectivity of the
column. The selectivity describes the 'uniqueness' of values in a column. A
selectivity of 100 means each value appears only once, and a selectivity
of 1 means the same value appears in many or most rows. For the query
above, the index on NAME should be used if the table contains more
distinct names than first names.
The SQL statement ANALYZE can be used to automatically estimate the
selectivity of the columns in the tables. This command should be run from
time to time to improve the query plans generated by the optimizer.
114 of 428
prep.setObject(1, new Long[] { 1L, 2L });
ResultSet rs = prep.executeQuery();
Optimization Examples
See src/test/org/h2/samples/optimizations.sql for a few examples of
queries that benefit from special optimizations built into the database.
Data Types
Each data type has different storage and performance characteristics:
• The DECIMAL/NUMERIC type is slower and requires more storage
than the REAL and DOUBLE PRECISION types.
• Text types are slower to read, write, and compare than numeric
types and generally require more storage.
• See Large Objects for information on BINARY vs. BLOB and VARCHAR
vs. CLOB performance.
• Parsing and formatting takes longer for the TIME, DATE, and
TIMESTAMP types than the numeric types.
• SMALLINT/TINYINT/BOOLEAN are not significantly smaller or faster to
work with than INTEGER in most modes.
115 of 428
Using the Built-In Profiler
A very simple Java profiler is built-in. To use it, use the following template:
import org.h2.util.Profiler;
Profiler prof = new Profiler();
prof.startCollecting();
// .... some long running process, at least a few seconds
prof.stopCollecting();
System.out.println(prof.getTop(3));
Application Profiling
Analyze First
Before trying to optimize performance, it is important to understand
where the problem is (what part of the application is slow). Blind
optimization or optimization based on guesses should be avoided,
because usually it is not an efficient strategy. There are various ways to
analyze an application. Sometimes two implementations can be compared
using System.currentTimeMillis(). But this does not work for complex
applications with many modules, and for memory problems.
A simple way to profile an application is to use the built-in profiling tool of
java. Example:
import org.h2.util;
...
Profiler profiler = new Profiler();
profiler.startCollecting();
// application code
System.out.println(profiler.getTop(3));
116 of 428
The profiler is built into the H2 Console tool, to analyze databases that
open slowly. To use it, run the H2 Console, and then click on 'Test
Connection'. Afterwards, click on "Test successful" and you get the most
common stack traces, which helps to find out why it took so long to
connect. You will only get the stack traces if opening the database took
more than a few seconds.
Database Profiling
The ConvertTraceFile tool generates SQL statement statistics at the end of
the SQL script file. The format used is similar to the profiling data
generated when using java -Xrunhprof. For this to work, the trace level
needs to be 2 or higher (TRACE_LEVEL_FILE=2). The easiest way to set the
trace level is to append the setting to the database URL, for example:
jdbc:h2:~/test;TRACE_LEVEL_FILE=2 or
jdbc:h2:tcp://localhost/~/test;TRACE_LEVEL_FILE=2. As an example,
execute the following script using the H2 Console:
SET TRACE_LEVEL_FILE 2;
DROP TABLE IF EXISTS TEST;
CREATE TABLE TEST(ID INT PRIMARY KEY, NAME VARCHAR(255));
@LOOP 1000 INSERT INTO TEST VALUES(?, ?);
SET TRACE_LEVEL_FILE 0;
After running the test case, convert the .trace.db file using the
ConvertTraceFile tool. The trace file is located in the same directory as the
database file.
The generated file test.sql will contain the SQL statements as well as the
following profiling data (results vary):
-----------------------------------------
-- SQL Statement Statistics
-- time: total time in milliseconds (accumulated)
-- count: how many times the statement ran
-- result: total update count or row count
-----------------------------------------
-- self accu time count result sql
-- 62% 62% 158 1000 1000 INSERT INTO TEST VALUES(?, ?);
117 of 428
-- 37% 100% 93 1 0 CREATE TABLE TEST(ID INT PRIMARY
KEY...
-- 0% 100% 0 1 0 DROP TABLE IF EXISTS TEST;
-- 0% 100% 0 1 0 SET TRACE_LEVEL_FILE 3;
For joins, the tables in the execution plan are sorted in the order they are
processed. The following query shows the database first processes the
table INVOICE (using the primary key). For each row, it will additionally
check that the value of the column AMOUNT is larger than zero, and for
those rows the database will search in the table CUSTOMER (using the
primary key). The query plan contains some redundancy so it is a valid
statement.
SELECT
I.ID,
C.NAME
FROM PUBLIC.INVOICE I
/* PUBLIC.PRIMARY_KEY_9: ID = 10 */
/* WHERE (I.ID = 10)
118 of 428
AND (AMOUNT > 0)
*/
INNER JOIN PUBLIC.CUSTOMER C
/* PUBLIC.PRIMARY_KEY_5: ID = I.CUSTOMER_ID */
ON 1=1
WHERE (C.ID = I.CUSTOMER_ID)
AND ((I.ID = 10)
AND (AMOUNT > 0))
The cache will prevent the pages are read twice. H2 reads all columns of
the row unless only the columns in the index are read. Except for large
CLOB and BLOB, which are not store in the table.
Special Optimizations
For certain queries, the database doesn't need to read all rows, or doesn't
need to sort the result even if ORDER BY is used.
For queries of the form SELECT COUNT(*), MIN(ID), MAX(ID) FROM TEST,
the query plan includes the line /* direct lookup */ if the data can be read
from an index.
119 of 428
For queries of the form SELECT DISTINCT CUSTOMER_ID FROM INVOICE,
the query plan includes the line /* distinct */ if there is an non-unique or
multi-column index on this column, and if this column has a low
selectivity.
For queries of the form SELECT * FROM TEST ORDER BY ID, the query plan
includes the line /* index sorted */ to indicate there is no separate sorting
required.
For queries of the form SELECT * FROM TEST GROUP BY ID ORDER BY ID,
the query plan includes the line /* group sorted */ to indicate there is no
separate sorting required.
120 of 428
EXPLAIN SELECT PHONE FROM ADDRESS WHERE NAME = 'Miller';
SELECT
PHONE
FROM PUBLIC.ADDRESS
/* PUBLIC.ADDRESS.tableScan */
WHERE NAME = 'Miller';
Indexes
An index internally is basically just a table that contains the indexed
column(s), plus the row id:
In the index, the data is sorted by the indexed columns. So this index
contains the following data:
CITY NAME FIRST_NAME _ROWID_
Berne Jones Philip 2
Berne Miller John 1
When the database uses an index to query the data, it searches the index
for the given data, and (if required) reads the remaining columns in the
main data table (retrieved using the row id). An index on city, name, and
first name (multi-column index) allows to quickly search for rows when the
city, name, and first name are known. If only the city and name, or only
the city is known, then this index is also used (so creating an additional
index on just the city is not needed). This index is also used when reading
all rows, sorted by the indexed columns. However, if only the first name is
known, then this index is not used:
121 of 428
AND ((CITY = 'Berne')
AND (NAME = 'Miller'));
If your application often queries the table for a phone number, then it
makes sense to create an additional index on it:
This index contains the phone number, and the row id:
PHONE _ROWID_
123 012 345 2
123 456 789 1
Using Multiple Indexes
Within a query, only one index per logical table is used. Using the
condition PHONE = '123 567 789' OR CITY = 'Berne' would use a table
scan instead of first using the index on the phone number and then the
122 of 428
index on the city. It makes sense to write two queries and combine then
using UNION. In this case, each individual query uses a different index:
EXPLAIN SELECT NAME FROM ADDRESS WHERE PHONE = '123 567 789'
UNION SELECT NAME FROM ADDRESS WHERE CITY = 'Berne';
(SELECT
NAME
FROM PUBLIC.ADDRESS
/* PUBLIC.IDX_PHONE: PHONE = '123 567 789' */
WHERE PHONE = '123 567 789')
UNION
(SELECT
NAME
FROM PUBLIC.ADDRESS
/* PUBLIC.INDEX_PLACE: CITY = 'Berne' */
WHERE CITY = 'Berne')
123 of 428
Advanced
Result Sets
Large Objects
Linked Tables
Spatial Features
Recursive Queries
Updatable Views
Transaction Isolation
Multi-Version Concurrency Control (MVCC)
Clustering / High Availability
Two Phase Commit
Compatibility
Keywords / Reserved Words
Standards Compliance
Run as Windows Service
ODBC Driver
ACID
Durability Problems
Using the Recover Tool
File Locking Protocols
Using Passwords
Password Hash
Protection against SQL Injection
Protection against Remote Access
Restricting Class Loading and Usage
Security Protocols
TLS Connections
Universally Unique Identifiers (UUID)
Settings Read from System Properties
Setting the Server Bind Address
Pluggable File System
Split File System
Java Objects Serialization
Limits and Limitations
Glossary and Links
124 of 428
Result Sets
Statements that Return a Result Set
The following statements return a result set: SELECT, TABLE, VALUES,
EXPLAIN, CALL, SCRIPT, SHOW, HELP. EXECUTE may return either a result
set or an update count. Result of a WITH statement depends on inner
command. All other statements return an update count.
Large Objects
Storing and Reading Large Objects
If it is possible that the objects don't fit into memory, then the data type
CLOB (for textual data) or BLOB (for binary data) should be used. For
these data types, the objects are not fully read into memory, by using
streams. To store a BLOB, use PreparedStatement.setBinaryStream. To
store a CLOB, use PreparedStatement.setCharacterStream. To read a
BLOB, use ResultSet.getBinaryStream, and to read a CLOB, use
ResultSet.getCharacterStream. When using the client/server mode, large
BLOB and CLOB data is stored in a temporary file on the client side.
Linked Tables
This database supports linked tables, which means tables that don't exist
in the current database but are just links to another database. To create
such a link, use the CREATE LINKED TABLE statement:
You can then access the table in the usual way. Whenever the linked table
is accessed, the database issues specific queries over JDBC. Using the
example above, if you issue the query SELECT * FROM LINK WHERE ID=1,
then the following query is run against the PostgreSQL database: SELECT *
FROM TEST WHERE ID=?. The same happens for insert and update
statements. Only simple statements are executed against the target
database, that means no joins (queries that contain joins are converted to
simple queries). Prepared statements are used where possible.
To view the statements that are executed against the target table, set the
trace level to 3.
If multiple linked tables point to the same database (using the same
database URL), the connection is shared. To disable this, set the system
property h2.shareLinkedConnections=false.
The statement CREATE LINKED TABLE supports an optional schema name
parameter.
The following are not supported because they may result in a deadlock:
creating a linked table to the same database, and creating a linked table
to another database using the server mode if the other database is open
in the same server (use the embedded mode instead).
Data types that are not supported in H2 are also not supported for linked
tables, for example unsigned data types if the value is outside the range
126 of 428
of the signed type. In such cases, the columns needs to be cast to a
supported type.
Updatable Views
By default, views are not updatable. To make a view updatable, use an
"instead of" trigger as follows:
Update the base table(s) within the trigger as required. For details, see
the sample application org.h2.samples.UpdatableView.
Transaction Isolation
Please note that most data definition language (DDL) statements, such as
"create table", commit the current transaction. See the Commands for
details.
Transaction isolation is provided for all data manipulation language (DML)
statements.
H2 supports read uncommitted, read committed, repeatable read,
snapshot, and serializable (partially, see below) isolation levels:
• Read uncommitted
Dirty reads, non-repeatable reads, and phantom reads are possible.
To enable, execute the SQL statement SET SESSION
CHARACTERISTICS AS TRANSACTION ISOLATION LEVEL READ
UNCOMMITTED
• Read committed
This is the default level. Dirty reads aren't possible; non-repeatable
reads and phantom reads are possible. To enable, execute the SQL
statement SET SESSION CHARACTERISTICS AS TRANSACTION
ISOLATION LEVEL READ COMMITTED
• Repeatable read
Dirty reads and non-repeatable reads aren't possible, phantom reads
are possible. To enable, execute the SQL statement SET SESSION
127 of 428
CHARACTERISTICS AS TRANSACTION ISOLATION LEVEL REPEATABLE
READ
• Snapshot
Dirty reads, non-repeatable reads, and phantom reads aren't
possible. This isolation level is very expensive in databases with
many tables. To enable, execute the SQL statement SET SESSION
CHARACTERISTICS AS TRANSACTION ISOLATION LEVEL SNAPSHOT
• Serializable
Dirty reads, non-repeatable reads, and phantom reads aren't
possible. Note that this isolation level in H2 currently doesn't ensure
equivalence of concurrent and serializable execution of transactions
that perform write operations. This isolation level is very expensive in
databases with many tables. To enable, execute the SQL statement
SET SESSION CHARACTERISTICS AS TRANSACTION ISOLATION LEVEL
SERIALIZABLE
• Dirty reads
Means a connection can read uncommitted changes made by
another connection.
Possible with: read uncommitted.
• Non-repeatable reads
A connection reads a row, another connection changes a row and
commits, and the first connection re-reads the same row and gets
the new result.
Possible with: read uncommitted, read committed.
• Phantom reads
A connection reads a set of rows using a condition, another
connection inserts a row that falls in this condition and commits, then
the first connection re-reads using the same condition and gets the
new row.
Possible with: read uncommitted, read committed, repeatable read.
Lock Timeout
If a connection cannot get a lock on an object, the connection waits for
some amount of time (the lock timeout). During this time, hopefully the
connection holding the lock commits and it is then possible to get the
lock. If this is not possible because the other connection does not release
the lock for some time, the unsuccessful connection will get a lock timeout
exception. The lock timeout can be set individually for each connection.
129 of 428
Using the CreateCluster Tool
To understand how clustering works, please try out the following example.
In this example, the two databases reside on the same computer, but
usually, the databases will be on different servers.
• Create two directories: server1, server2. Each directory will simulate
a directory on a computer.
• Start a TCP server pointing to the first directory. You can do this
using the command line:
java org.h2.tools.Server
-tcp -tcpPort 9101
-baseDir server1
• Start a second TCP server pointing to the second directory. This will
simulate a server running on a second (redundant) computer. You
can do this using the command line:
java org.h2.tools.Server
-tcp -tcpPort 9102
-baseDir server2
java org.h2.tools.CreateCluster
-urlSource jdbc:h2:tcp://localhost:9101/~/test
-urlTarget jdbc:h2:tcp://localhost:9102/~/test
-user sa
-serverList localhost:9101,localhost:9102
130 of 428
Detect Which Cluster Instances are Running
To find out which cluster nodes are currently running, execute the
following SQL statement:
If the result is '' (two single quotes), then the cluster mode is disabled.
Otherwise, the list of servers is returned, enclosed in single quote.
Example: 'server1:9191,server2:9191'.
It is also possible to get the list of servers by using
Connection.getClientInfo().
The property list returned from getClientInfo() contains a numServers
property that returns the number of servers that are in the connection list.
To get the actual servers, getClientInfo() also has properties
server0..serverX, where serverX is the number of servers minus 1.
Example: To get the 2nd server in the connection list one uses
getClientInfo('server1'). Note: The serverX property only returns IP
addresses and ports and not hostnames.
131 of 428
The SQL statement SET AUTOCOMMIT FALSE is not supported in the
cluster mode. To disable autocommit, the method
Connection.setAutoCommit(false) needs to be called.
It is possible that a transaction from one connection overtakes a
transaction from a different connection. Depending on the operations, this
might result in different results, for example when conditionally
incrementing a value in a row.
Compatibility
This database is (up to a certain point) compatible to other databases
such as HSQLDB, MySQL and PostgreSQL. There are certain areas where
H2 is incompatible.
SQL Standard
Keyword H2
2016 2011 2008 2003 1999 92
ALL + + + + + + +
AND + + + + + + +
ANY + + + + + + +
ARRAY + + + + + +
AS + + + + + + +
ASYMMETRIC + + + + + NR
AUTHORIZATION + + + + + + +
BETWEEN + + + + + NR +
BOTH CS + + + + + +
CASE + + + + + + +
CAST + + + + + + +
CHECK + + + + + + +
CONSTRAINT + + + + + + +
CROSS + + + + + + +
CURRENT_CATALOG + + + +
CURRENT_DATE + + + + + + +
CURRENT_PATH + + + + + +
CURRENT_ROLE + + + + + +
CURRENT_SCHEMA + + + +
CURRENT_TIME + + + + + + +
CURRENT_TIMESTAMP + + + + + + +
CURRENT_USER + + + + + + +
DAY + + + + + + +
DEFAULT + + + + + + +
133 of 428
SQL Standard
Keyword H2
2016 2011 2008 2003 1999 92
DISTINCT + + + + + + +
ELSE + + + + + + +
END + + + + + + +
EXCEPT + + + + + + +
EXISTS + + + + + NR +
FALSE + + + + + + +
FETCH + + + + + + +
FOR + + + + + + +
FOREIGN + + + + + + +
FROM + + + + + + +
FULL + + + + + + +
GROUP + + + + + + +
GROUPS CS + +
HAVING + + + + + + +
HOUR + + + + + + +
IF +
ILIKE CS
IN + + + + + + +
INNER + + + + + + +
INTERSECT + + + + + + +
INTERVAL + + + + + + +
IS + + + + + + +
JOIN + + + + + + +
KEY + NR NR NR NR + +
LEADING CS + + + + + +
LEFT + + + + + + +
LIKE + + + + + + +
LIMIT MS +
134 of 428
SQL Standard
Keyword H2
2016 2011 2008 2003 1999 92
LOCALTIME + + + + + +
LOCALTIMESTAMP + + + + + +
MINUS MS
MINUTE + + + + + + +
MONTH + + + + + + +
NATURAL + + + + + + +
NOT + + + + + + +
NULL + + + + + + +
OFFSET + + + +
ON + + + + + + +
OR + + + + + + +
ORDER + + + + + + +
OVER CS + + + +
PARTITION CS + + + +
PRIMARY + + + + + + +
QUALIFY +
RANGE CS + + + +
REGEXP CS
RIGHT + + + + + + +
ROW + + + + + +
ROWNUM +
ROWS CS + + + + + +
SECOND + + + + + + +
SELECT + + + + + + +
SESSION_USER + + + + + +
SET + + + + + + +
SOME + + + + + + +
SYMMETRIC + + + + + NR
135 of 428
SQL Standard
Keyword H2
2016 2011 2008 2003 1999 92
SYSTEM_USER + + + + + + +
TABLE + + + + + + +
TO + + + + + + +
MS
TOP
CS
TRAILING CS + + + + + +
TRUE + + + + + + +
UESCAPE + + + + +
UNION + + + + + + +
UNIQUE + + + + + + +
UNKNOWN + + + + + + +
USER + + + + + + +
USING + + + + + + +
VALUE + + + + + + +
VALUES + + + + + + +
WHEN + + + + + + +
WHERE + + + + + + +
WINDOW + + + + +
WITH + + + + + + +
YEAR + + + + + + +
_ROWID_ +
Mode-sensitive keywords (MS) are keywords only in some compatibility
modes.
• LIMIT is a keywords only in Regular, Legacy, DB2, HSQLDB, MariaDB,
MySQL, and PostgreSQL compatibility modes. It is an identifier in
Strict, Derby, MSSQLServer, and Oracle compatibility modes.
• MINUS is a keyword only in Regular, Legacy, DB2, HSQLDB, and
Oracle compatibility modes. It is an identifier in Strict, Derby,
MSSQLServer, MariaDB, MySQL, and PostgreSQL compatibility modes.
136 of 428
• TOP is a context-sensitive keyword (can be either keyword or
identifier) only in Regular, Legacy, HSQLDB, and MSSQLServer
compatibility modes. It is an identifier unconditionally in Strict,
Derby, DB2, MariaDB, MySQL, Oracle, and PostgreSQL compatibility
modes.
Context-sensitive keywords (CS) can be used as identifiers in some places,
but cannot be used as identifiers in others. Normal keywords (+) are
always treated as keywords.
Most keywords in H2 are also reserved (+) or non-reserved (NR) words in
the SQL Standard. Newer versions of H2 may have more keywords than
older ones. Reserved words from the SQL Standard are potential
candidates for keywords in future versions.
There is a compatibility setting SET NON_KEYWORDS that can be used as
a temporary workaround for applications that use keywords as unquoted
identifiers.
Standards Compliance
This database tries to be as much standard compliant as possible. For the
SQL language, ANSI/ISO is the main standard. There are several versions
that refer to the release date: SQL-92, SQL:1999, and SQL:2003.
Unfortunately, the standard documentation is not freely available. Another
problem is that important features are not standardized. Whenever this is
the case, this database tries to be compatible to other databases.
137 of 428
The service wrapper bundled with H2 is a 32-bit version. To use a 64-bit
version of Windows (x64), you need to use a 64-bit version of the wrapper,
for example the one from Simon Krenger.
When running the database as a service, absolute path should be used.
Using ~ in the database URL is problematic in this case, because it means
to use the home directory of the current user. The service might run
without or with the wrong user, so that the database files might end up in
an unexpected place.
138 of 428
Additional JDBC drivers
To use other databases (for example MySQL), the location of the JDBC
drivers of those databases need to be added to the environment variables
H2DRIVERS or CLASSPATH before installing the service. Multiple drivers
can be set; each entry needs to be separated with a ; (Windows) or :
(other operating systems). Spaces in the path names are supported. The
settings must not be quoted.
ODBC Driver
This database does not come with its own ODBC driver at this time, but it
supports the PostgreSQL network protocol. Therefore, the PostgreSQL
ODBC driver can be used. Support for the PostgreSQL network protocol is
quite new and should be viewed as experimental. It should not be used for
production applications.
To use the PostgreSQL ODBC driver on 64 bit versions of Windows, first
run c:/windows/syswow64/odbcad32.exe. At this point you set up your
DSN just like you would on any other system. See also: Re: ODBC Driver
on Windows 64 bit
ODBC Installation
First, the ODBC driver must be installed. Any recent PostgreSQL ODBC
driver should work, however version 8.2 (psqlodbc-08_02*) or newer is
recommended. The Windows version of the PostgreSQL ODBC driver is
available at https://www.postgresql.org/ftp/odbc/versions/msi/.
139 of 428
The PG server can be started and stopped from within a Java application
as follows:
ODBC Configuration
After installing the driver, a new Data Source must be added. In Windows,
run odbcad32.exe to open the Data Source Administrator. Then click on
'Add...' and select the PostgreSQL Unicode driver. Then click 'Finish'. You
will be able to change the connection properties. The property column
represents the property key in the odbc.ini file (which may be different
from the GUI).
Security Considerations
Currently, the PG Server does not support challenge response or encrypt
passwords. This may be a problem if an attacker can listen to the data
transferred between the ODBC driver and the server, because the
password is readable to the attacker. Also, it is currently not possible to
use encrypted SSL connections. Therefore the ODBC driver should not be
used where security is important.
The first connection that opens a database using the PostgreSQL server
needs to be an administrator user. Subsequent connections don't need to
be opened by an administrator.
ACID
In the database world, ACID stands for:
141 of 428
• Atomicity: transactions must be atomic, meaning either all tasks are
performed or none.
• Consistency: all operations must comply with the defined constraints.
• Isolation: transactions must be isolated from each other.
• Durability: committed transaction will not be lost.
Atomicity
Transactions in this database are always atomic.
Consistency
By default, this database is always in a consistent state. Referential
integrity rules are enforced except when explicitly disabled.
Isolation
For H2, as with most other database systems, the default isolation level is
'read committed'. This provides better performance, but also means that
transactions are not completely isolated. H2 supports the transaction
isolation levels 'read uncommitted', 'read committed', 'repeatable read',
and 'serializable'.
Durability
This database does not guarantee that all committed transactions survive
a power failure. Tests show that all databases sometimes lose
transactions on power failure (for details, see below). Where losing
transactions is not acceptable, a laptop or UPS (uninterruptible power
supply) should be used. If durability is required for all possible cases of
hardware failure, clustering should be used, such as the H2 clustering
mode.
Durability Problems
Complete durability means all committed transaction survive a power
failure. Some databases claim they can guarantee durability, but such
claims are wrong. A durability test was run against H2, HSQLDB,
PostgreSQL, and Derby. All of those databases sometimes lose committed
transactions. The test is included in the H2 download, see
org.h2.test.poweroff.Test.
142 of 428
Ways to (Not) Achieve Durability
Making sure that committed transactions are not lost is more complicated
than it seems first. To guarantee complete durability, a database must
ensure that the log record is on the hard drive before the commit call
returns. To do that, databases use different methods. One is to use the
'synchronous write' file access mode. In Java, RandomAccessFile supports
the modes rws and rwd:
• rwd: every update to the file's content is written synchronously to the
underlying storage device.
• rws: in addition to rwd, every update to the metadata is written
synchronously.
A test (org.h2.test.poweroff.TestWrite) with one of those modes achieves
around 50 thousand write operations per second. Even when the
operating system write buffer is disabled, the write rate is around 50
thousand operations per second. This feature does not force changes to
disk because it does not flush all buffers. The test updates the same byte
in the file again and again. If the hard drive was able to write at this rate,
then the disk would need to make at least 50 thousand revolutions per
second, or 3 million RPM (revolutions per minute). There are no such hard
drives. The hard drive used for the test is about 7200 RPM, or about 120
revolutions per second. There is an overhead, so the maximum write rate
must be lower than that.
Calling fsync flushes the buffers. There are two ways to do that in Java:
• FileDescriptor.sync(). The documentation says that this forces all
system buffers to synchronize with the underlying device. This
method is supposed to return after all in-memory modified copies of
buffers associated with this file descriptor have been written to the
physical medium.
• FileChannel.force(). This method is supposed to force any updates to
this channel's file to be written to the storage device that contains it.
By default, MySQL calls fsync for each commit. When using one of those
methods, only around 60 write operations per second can be achieved,
which is consistent with the RPM rate of the hard drive used.
Unfortunately, even when calling FileDescriptor.sync() or
FileChannel.force(), data is not always persisted to the hard drive,
because most hard drives do not obey fsync(): see Your Hard Drive Lies to
143 of 428
You. In Mac OS X, fsync does not flush hard drive buffers. See Bad fsync?.
So the situation is confusing, and tests prove there is a problem.
Trying to flush hard drive buffers is hard, and if you do the performance is
very bad. First you need to make sure that the hard drive actually flushes
all buffers. Tests show that this can not be done in a reliable way. Then
the maximum number of transactions is around 60 per second. Because of
those reasons, the default behavior of H2 is to delay writing committed
transactions.
In H2, after a power failure, a bit more than one second of committed
transactions may be lost. To change the behavior, use SET WRITE_DELAY
and CHECKPOINT SYNC. Most other databases support commit delay as
well. In the performance comparison, commit delay was used for all
databases that support it.
For each database in the current directory, a text file will be created. This
file contains raw insert statements (for the data) and data definition (DDL)
statements to recreate the schema of the database. This file can be
executed using the RunScript tool or a RUNSCRIPT SQL statement. The
script includes at least one CREATE USER statement. If you run the script
against a database that was created with the same user, or if there are
conflicting users, running the script will fail. Consider running the script
against a database that was created with a user name that is not in the
script.
The Recover tool creates a SQL script from database file. It also processes
the transaction log.
To verify the database can recover at any time, append
;RECOVER_TEST=64 to the database URL in your test environment. This
will simulate an application crash after each 64 writes to the database file.
A log file named databaseName.h2.db.log is created that lists the
operations. The recovery is tested using an in-memory file system, that
means it may require a larger heap setting.
145 of 428
simplicity (that is, the lock file does not need to be deleted manually by
the user). The two methods are 'file method' and 'socket methods'.
The file locking protocols (except the file locking method 'FS') have the
following limitation: if a shared file system is used, and the machine with
the lock owner is sent to sleep (standby or hibernate), another machine
may take over. If the machine that originally held the lock wakes up, the
database may become corrupt. If this situation can occur, the application
must ensure the database is closed when the application is put to sleep.
146 of 428
this thread. In this case, the file is deleted and atomically created
again. The watchdog thread is started in this case and the file is
locked.
This algorithm is tested with over 100 concurrent threads. In some cases,
when there are many concurrent threads trying to lock the database, they
block each other (meaning the file cannot be locked by any of them) for
some time. However, the file never gets locked by two threads at the
same time. However using that many concurrent threads / processes is
not the common use case. Generally, an application should throw an error
to the user if it cannot open a database, and not try again in a (fast) loop.
Using Passwords
Using Secure Passwords
Remember that weak passwords can be broken regardless of the
encryption and security protocols. Don't use passwords that can be found
in a dictionary. Appending numbers does not make passwords secure. A
way to create good passwords that can be remembered is: take the first
letters of a sentence, use upper and lower case characters, and creatively
include special characters (but it's more important to use a long password
than to use special characters). Example:
i'sE2rtPiUKtT from the sentence it's easy to remember this password if you
know the trick.
148 of 428
import java.sql.*;
import java.util.*;
public class Test {
public static void main(String[] args) throws Exception {
String url = "jdbc:h2:~/test";
Properties prop = new Properties();
prop.setProperty("user", "sa");
System.out.print("Password?");
char[] password = System.console().readPassword();
prop.put("password", password);
Connection conn = null;
try {
conn = DriverManager.getConnection(url, prop);
} finally {
Arrays.fill(password, (char) 0);
}
conn.close();
}
}
Password Hash
Sometimes the database password needs to be stored in a configuration
file (for example in the web.xml file). In addition to connecting with the
plain text password, this database supports connecting with the password
hash. This means that only the hash of the password (and not the plain
text password) needs to be stored in the configuration file. This will only
protect others from reading or re-constructing the plain text password
(even if they have access to the configuration file); it does not protect
others from accessing the database using the password hash.
149 of 428
To connect using the password hash instead of plain text password,
append ;PASSWORD_HASH=TRUE to the database URL, and replace the
password with the password hash. To calculate the password hash from a
plain text password, run the following command within the H2 Console
tool: @password_hash <upperCaseUserName> <password>. As an
example, if the user name is sa and the password is test, run the
command @password_hash SA test. Then use the resulting password hash
as you would use the plain text password. When using an encrypted
database, then the user password and file password need to be hashed
separately. To calculate the hash of the file password, run:
@password_hash file <filePassword>.
Which is always true no matter what the password stored in the database
is. For more information about SQL Injection, see Glossary and Links.
Disabling Literals
SQL Injection is not possible if user input is not directly embedded in SQL
statements. A simple solution for the problem above is to use a prepared
statement:
Afterwards, SQL statements with text and number literals are not allowed
any more. That means, SQL statement of the form WHERE NAME='abc' or
WHERE CustomerId=10 will fail. It is still possible to use prepared
statements and parameters as described above. Also, it is still possible to
generate SQL statements dynamically, and use the Statement API, as long
as the SQL statements do not include literals. There is also a second mode
where number literals are allowed: SET ALLOW_LITERALS NUMBERS. To
allow all literals, execute SET ALLOW_LITERALS ALL (this is the default
setting). Literals can only be enabled or disabled by an administrator.
Using Constants
Disabling literals also means disabling hard-coded 'constant' literals. This
database supports defining constants using the CREATE CONSTANT
command. Constants can be defined only when literals are enabled, but
used even when literals are disabled. To avoid name clashes with column
names, constants can be defined in other schemas:
151 of 428
SELECT * FROM USERS WHERE LENGTH(PASSWORD)=ZERO();
java -Dh2.allowedClasses=java.lang.Math,com.acme.*
152 of 428
This mechanism is used for all user classes, including database event
listeners, trigger classes, user-defined functions, user-defined aggregate
functions, and JDBC driver classes (with the exception of the H2 driver)
when using the H2 Console.
Security Protocols
The following paragraphs document the security protocols used in this
database. These descriptions are very technical and only intended for
security experts that already know the underlying security primitives.
153 of 428
by storing it on another computer and only accessible remotely, then the
iteration count is not required at all.
File Encryption
The database files can be encrypted using the AES-128 algorithm.
When a user tries to connect to an encrypted database, the combination
of file@ and the file password is hashed using SHA-256. This hash value is
transmitted to the server.
When a new database file is created, a new cryptographically secure
random salt value is generated. The size of the salt is 64 bits. The
combination of the file password hash and the salt value is hashed 1024
times using SHA-256. The reason for the iteration is to make it harder for
an attacker to calculate hash values for common passwords.
The resulting hash value is used as the key for the block cipher algorithm.
Then, an initialization vector (IV) key is calculated by hashing the key
again using SHA-256. This is to make sure the IV is unknown to the
attacker. The reason for using a secret IV is to protect against watermark
attacks.
Before saving a block of data (each block is 8 bytes long), the following
operations are executed: first, the IV is calculated by encrypting the block
number with the IV key (using the same block cipher algorithm). This IV is
combined with the plain text using XOR. The resulting data is encrypted
using the AES-128 algorithm.
When decrypting, the operation is done in reverse. First, the block is
decrypted using the key, and then the IV is calculated combined with the
decrypted text using XOR.
Therefore, the block cipher mode of operation is CBC (cipher-block
chaining), but each chain is only one block long. The advantage over the
ECB (electronic codebook) mode is that patterns in the data are not
revealed, and the advantage over multi block CBC is that flipped cipher
text bits are not propagated to flipped plaintext bits in the next block.
Database encryption is meant for securing the database while it is not in
use (stolen laptop and so on). It is not meant for cases where the attacker
has access to files while the database is in use. When he has write access,
154 of 428
he can for example replace pieces of files with pieces of older versions
and manipulate data like this.
File encryption slows down the performance of the database engine.
Compared to unencrypted mode, database operations take about 2.5
times longer using AES (embedded mode).
HTTPS Connections
The web server supports HTTP and HTTPS connections using
SSLServerSocket. There is a default self-certified certificate to support an
easy starting point, but custom certificates are supported as well.
TLS Connections
Remote TLS connections are supported using the Java Secure Socket
Extension (SSLServerSocket, SSLSocket). By default, anonymous TLS is
enabled.
To use your own keystore, set the system properties
javax.net.ssl.keyStore and javax.net.ssl.keyStorePassword before starting
the H2 server and client. See also Customizing the Default Key and Trust
Stores, Store Types, and Store Passwords for more information.
155 of 428
To disable anonymous TLS, set the system property
h2.enableAnonymousTLS to false.
156 of 428
Spatial Features
H2 supports the geometry data type and spatial indexes. Here is an
example SQL script to create a table with a spatial column and index:
You can verify that the spatial index is used using the "explain plan"
feature:
For persistent databases, the spatial index is stored on disk; for in-
memory databases, the index is kept in memory.
157 of 428
Recursive Queries
H2 has experimental support for recursive queries using so called
"common table expressions" (CTE). Examples:
Limitations: Recursive queries need to be of the type UNION ALL, and the
recursion needs to be on the second part of the query. No tables or views
with the name of the table expression may exist. Different table
expression names need to be used when using multiple distinct table
158 of 428
expressions within the same transaction and for the same session. All
columns of the table expression are of type VARCHAR, and may need to
be cast to the required data type. Views with recursive queries are not
supported. Subqueries and INSERT INTO ... FROM with recursive queries
are not supported. Parameters are only supported within the last SELECT
statement (a workaround is to use session variables like @start within the
table expression). The syntax is:
160 of 428
Split File System
The file system prefix split: is used to split logical files into multiple
physical files, for example so that a database can get larger than the
maximum file system size of the operating system. If the logical file is
larger than the maximum file size, then the file is split as follows:
• <fileName> (first block, is always created)
• <fileName>.1.part (second block)
More physical files (*.2.part, *.3.part) are automatically created / deleted if
needed. The maximum physical file size of a block is 2^30 bytes, which is
also called 1 GiB or 1 GB. However this can be changed if required, by
specifying the block size in the file name. The file name format is:
split:<x>:<fileName> where the file size per block is 2^x. For 1 MiB block
sizes, use x = 20 (because 2^20 is 1 MiB). The following file name means
the logical file is split into 1 MiB blocks: split:20:~/test.h2.db. An example
database URL for this case is jdbc:h2:split:20:~/test.
161 of 428
Please note that this SQL statement can only be executed before any
tables are defined.
162 of 428
• There is no limit for the following entities, except the memory and
storage capacity: maximum number of tables, indexes, triggers, and
other database objects; maximum statement length, tables per
statement; maximum rows per query; maximum indexes per table,
lob columns per table, and so on; maximum row length, index row
length, select row length.
• Querying from the metadata tables is slow if there are many tables
(thousands).
• For other limitations on data types, see the data type documentation
of this database.
163 of 428
Secure Sockets Layer / Transport Layer Security. See also:
SSL/TLS
Java Secure Socket Extension (JSSE)
164 of 428
Commands
Index
Commands (Data Manipulation)
SELECT
INSERT
UPDATE
DELETE
BACKUP
CALL
EXECUTE IMMEDIATE
EXPLAIN
MERGE INTO
MERGE USING
RUNSCRIPT
SCRIPT
SHOW
Explicit table
Table value
WITH
166 of 428
Commands (Other)
CHECKPOINT
CHECKPOINT SYNC
COMMIT
COMMIT TRANSACTION
GRANT RIGHT
GRANT ALTER ANY SCHEMA
GRANT ROLE
HELP
PREPARE COMMIT
REVOKE RIGHT
REVOKE ALTER ANY SCHEMA
REVOKE ROLE
ROLLBACK
ROLLBACK TRANSACTION
SAVEPOINT
SET @
SET ALLOW_LITERALS
SET AUTOCOMMIT
SET CACHE_SIZE
SET CLUSTER
SET BUILTIN_ALIAS_OVERRIDE
SET CATALOG
SET COLLATION
SET DATABASE_EVENT_LISTENER
SET DB_CLOSE_DELAY
SET DEFAULT_LOCK_TIMEOUT
SET DEFAULT_NULL_ORDERING
SET DEFAULT_TABLE_TYPE
SET EXCLUSIVE
SET IGNORECASE
SET IGNORE_CATALOGS
SET JAVA_OBJECT_SERIALIZER
SET LAZY_QUERY_EXECUTION
SET LOCK_MODE
SET LOCK_TIMEOUT
SET MAX_LENGTH_INPLACE_LOB
SET MAX_LOG_SIZE
167 of 428
SET MAX_MEMORY_ROWS
SET MAX_MEMORY_UNDO
SET MAX_OPERATION_MEMORY
SET MODE
SET NON_KEYWORDS
SET OPTIMIZE_REUSE_RESULTS
SET PASSWORD
SET QUERY_STATISTICS
SET QUERY_STATISTICS_MAX_ENTRIES
SET QUERY_TIMEOUT
SET REFERENTIAL_INTEGRITY
SET RETENTION_TIME
SET SALT HASH
SET SCHEMA
SET SCHEMA_SEARCH_PATH
SET SESSION CHARACTERISTICS
SET THROTTLE
SET TIME ZONE
SET TRACE_LEVEL
SET TRACE_MAX_FILE_SIZE
SET TRUNCATE_LARGE_LENGTH
SET VARIABLE_BINARY
SET WRITE_DELAY
SHUTDOWN
Details
Non-standard syntax is marked in green. Compatibility-only non-standard
syntax is marked in red, don't use it unless you need it for compatibility
with other databases or old versions of H2.
INSERT
INSERT INTO [schemaName.]tableName [ ( columnName [,...] ) ]
{ [ overrideClause ] { insertValues | [ DIRECT ] query } }
| DEFAULT VALUES
UPDATE
UPDATE [schemaName.]tableName [ [ AS ] newTableAlias ] SET
setClauseList
[ WHERE expression ] [ ORDER BY sortSpecificationList ]
FETCH { FIRST | NEXT } [ expression ] { ROW | ROWS } ONLY
DELETE
DELETE FROM [schemaName.]tableName
[ WHERE expression ]
FETCH { FIRST | NEXT } [ expression ] { ROW | ROWS } ONLY
171 of 428
Deletes rows form a table. If FETCH is specified, at most the specified
number of rows are deleted (no limit if null or smaller than zero).
Example:
DELETE FROM TEST WHERE ID=2
BACKUP
BACKUP TO fileNameString
Backs up the database files to a .zip file. Objects are not locked, but the
backup is transactionally consistent because the transaction log is also
copied. Admin rights are required to execute this command.
Example:
BACKUP TO 'backup.zip'
CALL
CALL expression
EXECUTE IMMEDIATE
EXECUTE IMMEDIATE sqlString
Shows the execution plan for a statement. When using EXPLAIN ANALYZE,
the statement is actually executed, and the query plan will include the
actual row scan count for each table.
Example:
EXPLAIN SELECT * FROM TEST WHERE ID=1
MERGE INTO
MERGE INTO [schemaName.]tableName [ ( columnName [,...] ) ]
[ KEY ( columnName [,...] ) ]
{ insertValues | query }
Updates existing rows, and insert rows that don't exist. If no key column is
specified, the primary key columns are used to find the row. If more than
one row per new row is affected, an exception is thrown.
Example:
MERGE INTO TEST KEY(ID) VALUES(2, 'World')
MERGE USING
MERGE INTO [schemaName.]targetTableName [ [AS] targetAlias]
USING tableExpression
ON expression
mergeWhenClause [,...]
Updates or deletes existing rows, and insert rows that don't exist.
The ON clause specifies the matching column expression.
Different rows from a source table may not match with the same target
row (this is not ensured by H2 if target table is an updatable view). One
source row may be matched with multiple target rows.
If statement doesn't need a source table a DUAL table can be substituted.
Example:
173 of 428
MERGE INTO TARGET_TABLE AS T USING SOURCE_TABLE AS S
ON T.ID = S.ID
WHEN MATCHED AND T.COL2 <> 'FINAL' THEN
UPDATE SET T.COL1 = S.COL1
WHEN MATCHED AND T.COL2 = 'FINAL' THEN
DELETE
WHEN NOT MATCHED THEN
INSERT (ID, COL1, COL2) VALUES(S.ID, S.COL1, S.COL2);
MERGE INTO TARGET_TABLE AS T USING (SELECT * FROM SOURCE_TABLE)
AS S
ON T.ID = S.ID
WHEN MATCHED AND T.COL2 <> 'FINAL' THEN
UPDATE SET T.COL1 = S.COL1
WHEN MATCHED AND T.COL2 = 'FINAL' THEN
DELETE
WHEN NOT MATCHED THEN
INSERT VALUES (S.ID, S.COL1, S.COL2);
MERGE INTO TARGET T USING (VALUES (1, 4), (2, 15)) S(ID, V)
ON T.ID = S.ID
WHEN MATCHED THEN UPDATE SET V = S.V
WHEN NOT MATCHED THEN INSERT VALUES (S.ID, S.V);
MERGE INTO TARGET_TABLE USING DUAL ON ID = 1
WHEN NOT MATCHED THEN INSERT VALUES (1, 'Test')
WHEN MATCHED THEN UPDATE SET NAME = 'Test';
RUNSCRIPT
RUNSCRIPT FROM fileNameString scriptCompressionEncryption
[ CHARSET charsetString ]
{ [ QUIRKS_MODE ] [ VARIABLE_BINARY ] | FROM_1X }
Runs a SQL script from a file. The script is a text file containing SQL
statements; each statement must end with ';'. This command can be used
to restore a database from a backup. The password must be in single
quotes; it is case sensitive and can contain spaces.
Instead of a file name, a URL may be used. To read a stream from the
classpath, use the prefix 'classpath:'. See the Pluggable File System
section.
174 of 428
The compression algorithm must match the one used when creating the
script. Instead of a file, a URL may be used.
If QUIRKS_MODE is specified, the various compatibility quirks for scripts
from older versions of H2 are enabled. Use this clause when you import
script that was generated by H2 1.4.200 or an older version into more
recent version.
If VARIABLE_BINARY is specified, the BINARY data type will be parsed as
VARBINARY. Use this clause when you import script that was generated by
H2 1.4.200 or an older version into more recent version.
If FROM_1X is specified, quirks for scripts exported from H2 1.*.* are
enabled. Use this flag to populate a new database with the data exported
from 1.*.* versions of H2. This flag also enables QUIRKS_MODE and
VARIABLE_BINARY implicitly.
Admin rights are required to execute this command.
Example:
RUNSCRIPT FROM 'backup.sql'
RUNSCRIPT FROM 'classpath:/com/acme/test.sql'
RUNSCRIPT FROM 'dump_from_1_4_200.sql' FROM_1X
SCRIPT
SCRIPT { [ NODATA ] | [ SIMPLE ] [ COLUMNS ] }
[ NOPASSWORDS ] [ NOSETTINGS ]
[ DROP ] [ BLOCKSIZE blockSizeInt ]
[ TO fileNameString scriptCompressionEncryption
[ CHARSET charsetString ] ]
[ TABLE [schemaName.]tableName [, ...] ]
[ SCHEMA schemaName [, ...] ]
175 of 428
line commands. NOSETTINGS turns off dumping the database settings (the
SET XXX commands)
If no 'TO fileName' clause is specified, the script is returned as a result set.
This command can be used to create a backup of the database. For long
term storage, it is more portable than copying the database files.
If a 'TO fileName' clause is specified, then the whole script (including
insert statements) is written to this file, and a result set without the insert
statements is returned.
The password must be in single quotes; it is case sensitive and can
contain spaces.
This command locks objects while it is running. Admin rights are required
to execute this command.
When using the TABLE or SCHEMA option, only the selected table(s) /
schema(s) are included.
Example:
SCRIPT NODATA
SHOW
SHOW { SCHEMAS | TABLES [ FROM schemaName ] |
COLUMNS FROM tableName [ FROM schemaName ] }
Explicit table
TABLE [schemaName.]tableName
[ ORDER BY selectOrder [,...] ]
[ OFFSET expression { ROW | ROWS } ]
[ FETCH { FIRST | NEXT } [ expression [ PERCENT ] ] { ROW | ROWS }
{ ONLY | WITH TIES } ]
Table value
VALUES rowValueExpression [,...]
[ ORDER BY selectOrder [,...] ]
[ OFFSET expression { ROW | ROWS } ]
[ FETCH { FIRST | NEXT } [ expression [ PERCENT ] ] { ROW | ROWS }
{ ONLY | WITH TIES } ]
A list of rows that can be used like a table. See See SELECT command for
description of ORDER BY, OFFSET, and FETCH. The column list of the
resulting table is C1, C2, and so on.
Example:
VALUES (1, 'Hello'), (2, 'World');
WITH
WITH [ RECURSIVE ] { name [( columnName [,...] )] AS ( query ) [,...] }
{ query | { insert | update | delete | mergeInto | mergeUsing |
createTable } }
179 of 428
Renames a constraint. This command commits an open transaction in this
connection.
Example:
ALTER DOMAIN D RENAME CONSTRAINT FOO TO BAR
ALTER SEQUENCE
ALTER SEQUENCE [ IF EXISTS ] [schemaName.]sequenceName
alterSequenceOption [...]
181 of 428
ALTER TABLE ALTER COLUMN
ALTER TABLE [ IF EXISTS ] [schemaName.]tableName
ALTER COLUMN [ IF EXISTS ] columnName
{ { columnDefinition }
| { RENAME TO name }
| SET GENERATED { ALWAYS | BY DEFAULT } [ alterIdentityColumnOption
[...] ]
| alterIdentityColumnOption [...]
| DROP IDENTITY
| { SELECTIVITY int }
| { SET DEFAULT expression }
| { DROP DEFAULT }
| DROP EXPRESSION
| { SET ON UPDATE expression }
| { DROP ON UPDATE }
| { SET DEFAULT ON NULL }
| { DROP DEFAULT ON NULL }
| { SET NOT NULL }
| { DROP NOT NULL } | { SET NULL }
| { SET DATA TYPE dataTypeOrDomain [ USING newValueExpression ] }
| { SET { VISIBLE | INVISIBLE } } }
Changes the data type of a column, rename a column, change the identity
value, or change the selectivity.
Changing the data type fails if the data can not be converted.
SET GENERATED ALWAYS, SET GENERATED BY DEFAULT, or identity
options convert the column into identity column (if it wasn't an identity
column) and set new values of specified options for its sequence.
DROP IDENTITY removes identity status of a column.
SELECTIVITY sets the selectivity (1-100) for a column. Setting the
selectivity to 0 means the default value. Selectivity is used by the cost
based optimizer to calculate the estimated cost of an index. Selectivity
100 means values are unique, 10 means every distinct value appears 10
times on average.
SET DEFAULT changes the default value of a column. This command
doesn't affect generated and identity columns.
DROP DEFAULT removes the default value of a column.
DROP EXPRESSION converts generated column into base column.
182 of 428
SET ON UPDATE changes the value that is set on update if value for this
column is not specified in update statement. This command doesn't affect
generated and identity columns.
DROP ON UPDATE removes the value that is set on update of a column.
SET DEFAULT ON NULL makes NULL value work as DEFAULT value is
assignments to this column.
DROP DEFAULT ON NULL makes NULL value work as NULL value in
assignments to this column.
SET NOT NULL sets a column to not allow NULL. Rows may not contain
NULL in this column.
DROP NOT NULL and SET NULL set a column to allow NULL. The column
may not be part of a primary key and may not be an identity column.
SET DATA TYPE changes the data type of a column, for each row old value
is converted to this data type unless USING is specified with a custom
expression. USING expression may reference previous value of the
modified column by its name and values of other columns.
SET INVISIBLE makes the column hidden, i.e. it will not appear in SELECT *
results. SET VISIBLE has the reverse effect.
This command commits an open transaction in this connection.
Example:
ALTER TABLE TEST ALTER COLUMN NAME CLOB;
ALTER TABLE TEST ALTER COLUMN NAME RENAME TO TEXT;
ALTER TABLE TEST ALTER COLUMN ID RESTART WITH 10000;
ALTER TABLE TEST ALTER COLUMN NAME SELECTIVITY 100;
ALTER TABLE TEST ALTER COLUMN NAME SET DEFAULT '';
ALTER TABLE TEST ALTER COLUMN NAME SET NOT NULL;
ALTER TABLE TEST ALTER COLUMN NAME SET NULL;
ALTER TABLE TEST ALTER COLUMN NAME SET VISIBLE;
ALTER TABLE TEST ALTER COLUMN NAME SET INVISIBLE;
183 of 428
Removes column(s) from a table. This command commits an open
transaction in this connection.
Example:
ALTER TABLE TEST DROP COLUMN NAME
ALTER TABLE TEST DROP COLUMN (NAME1, NAME2)
184 of 428
Renames a table. This command commits an open transaction in this
connection.
Example:
ALTER TABLE TEST RENAME TO MY_DATA
185 of 428
Admin rights are required to execute this command. This command
commits an open transaction in this connection.
Example:
ALTER USER SA SET PASSWORD 'rioyxlgt'
ANALYZE
ANALYZE [ TABLE [schemaName.]tableName ] [ SAMPLE_SIZE
rowCountInt ]
COMMENT ON
COMMENT ON
{ { COLUMN [schemaName.]tableName.columnName }
| { { TABLE | VIEW | CONSTANT | CONSTRAINT | ALIAS | INDEX | ROLE
| SCHEMA | SEQUENCE | TRIGGER | USER | DOMAIN }
[schemaName.]objectName } }
IS expression
CREATE AGGREGATE
CREATE AGGREGATE [ IF NOT EXISTS ] [schemaName.]aggregateName
FOR classNameString
CREATE ALIAS
CREATE ALIAS [ IF NOT EXISTS ] [schemaName.]functionAliasName
[ DETERMINISTIC ]
{ FOR classAndMethodString | AS sourceCodeString }
187 of 428
Creates a new function alias. If this is a ResultSet returning function, by
default the return value is cached in a local temporary file.
DETERMINISTIC - Deterministic functions must always return the same
value for the same parameters.
The method name must be the full qualified class and method name, and
may optionally include the parameter classes as in
java.lang.Integer.parseInt(java.lang.String, int). The class and the method
must both be public, and the method must be static. The class must be
available in the classpath of the database engine (when using the server
mode, it must be in the classpath of the server).
When defining a function alias with source code, the Sun javac is compiler
is used if the file tools.jar is in the classpath. If not, javac is run as a
separate process. Only the source code is stored in the database; the
class is compiled each time the database is re-opened. Source code is
usually passed as dollar quoted text to avoid escaping problems. If import
statements are used, then the tag @CODE must be added before the
method.
If the method throws an SQLException, it is directly re-thrown to the
calling application; all other exceptions are first converted to a
SQLException.
If the first parameter of the Java function is a java.sql.Connection, then a
connection to the database is provided. This connection must not be
closed. If the class contains multiple methods with the given name but
different parameter count, all methods are mapped.
Admin rights are required to execute this command. This command
commits an open transaction in this connection.
If you have the Groovy jar in your classpath, it is also possible to write
methods using Groovy.
Example:
CREATE ALIAS MY_SQRT FOR 'java.lang.Math.sqrt';
CREATE ALIAS MY_ROUND FOR 'java.lang.Math.round(double)';
CREATE ALIAS GET_SYSTEM_PROPERTY FOR
'java.lang.System.getProperty';
CALL GET_SYSTEM_PROPERTY('java.class.path');
CALL GET_SYSTEM_PROPERTY('com.acme.test', 'true');
188 of 428
CREATE ALIAS REVERSE AS 'String reverse(String s) { return new
StringBuilder(s).reverse().toString(); }';
CALL REVERSE('Test');
CREATE ALIAS tr AS '@groovy.transform.CompileStatic
static String tr(String str, String sourceSet, String replacementSet){
return str.tr(sourceSet, replacementSet);
}
'
CREATE CONSTANT
CREATE CONSTANT [ IF NOT EXISTS ] [schemaName.]constantName
VALUE expression
Creates a new constant. Schema owner rights are required to execute this
command. This command commits an open transaction in this connection.
Example:
CREATE CONSTANT ONE VALUE 1
CREATE DOMAIN
CREATE DOMAIN [ IF NOT EXISTS ] [schemaName.]domainName
[ AS ] dataTypeOrDomain
[ DEFAULT expression ]
[ ON UPDATE expression ]
[ COMMENT expression ]
[ CHECK (condition) ] [...]
189 of 428
CREATE INDEX
CREATE [ UNIQUE | SPATIAL ] INDEX
[ [ IF NOT EXISTS ] [schemaName.]indexName ]
ON [schemaName.]tableName ( indexColumn [,...] )
[ INCLUDE ( indexColumn [,...] ) ]
Creates a table link to an external table. The driver name may be empty if
the driver is already loaded. If the schema name is not set, only one table
with that name may exist in the target database.
FORCE - Create the LINKED TABLE even if the remote database/table does
not exist.
EMIT UPDATES - Usually, for update statements, the old rows are deleted
first and then the new rows are inserted. It is possible to emit update
statements (except on rollback), however in this case multi-row unique
key updates may not always work. Linked tables to the same database
share one connection.
190 of 428
READONLY - is set, the remote table may not be updated. This is enforced
by H2.
FETCH_SIZE - the number of rows fetched, a hint with non-negative
number of rows to fetch from the external table at once, may be ignored
by the driver of external database. 0 is default and means no hint. The
value is passed to java.sql.Statement.setFetchSize() method.
AUTOCOMMIT - is set to ON, the auto-commit mode is enable. OFF is
disable. The value is passed to java.sql.Connection.setAutoCommit()
method.
If the connection to the source database is lost, the connection is re-
opened (this is a workaround for MySQL that disconnects after 8 hours of
inactivity by default).
If a query is used instead of the original table name, the table is read only.
Queries must be enclosed in parenthesis: (SELECT * FROM ORDERS).
To use JNDI to get the connection, the driver class must be a
javax.naming.Context (for example javax.naming.InitialContext), and the
URL must be the resource name (for example java:comp/env/jdbc/Test).
Admin rights are required to execute this command. This command
commits an open transaction in this connection.
Example:
CREATE LINKED TABLE LINK('org.h2.Driver', 'jdbc:h2:./test2',
'sa', 'sa', 'TEST');
CREATE LINKED TABLE LINK('', 'jdbc:h2:./test2', 'sa', 'sa',
'(SELECT * FROM TEST WHERE ID>0)');
CREATE LINKED TABLE LINK('javax.naming.InitialContext',
'java:comp/env/jdbc/Test', NULL, NULL,
'(SELECT * FROM TEST WHERE ID>0)');
CREATE ROLE
CREATE ROLE [ IF NOT EXISTS ] newRoleName
191 of 428
CREATE ROLE READONLY
CREATE SCHEMA
CREATE SCHEMA [ IF NOT EXISTS ]
{ name [ AUTHORIZATION ownerName ] | [ AUTHORIZATION
ownerName ] }
[ WITH tableEngineParamName [,...] ]
Creates a new schema. Schema admin rights are required to execute this
command.
If schema name is not specified, the owner name is used as a schema
name. If schema name is specified, but no owner is specified, the current
user is used as an owner.
Schema owners can create, rename, and drop objects in the schema.
Schema owners can drop the schema itself, but cannot rename it. Some
objects may still require admin rights for their creation, see
documentation of their CREATE statements for details.
Optional table engine parameters are used when CREATE TABLE
command is run on this schema without having its engine params set.
This command commits an open transaction in this connection.
Example:
CREATE SCHEMA TEST_SCHEMA AUTHORIZATION SA
CREATE SEQUENCE
CREATE SEQUENCE [ IF NOT EXISTS ] [schemaName.]sequenceName
[ { AS dataType | sequenceOption } [...] ]
CREATE TABLE
CREATE [ CACHED | MEMORY ] [ { TEMP } | [ GLOBAL | LOCAL ]
TEMPORARY ]
TABLE [ IF NOT EXISTS ] [schemaName.]tableName
[ ( { columnName [columnDefinition] | tableConstraintDefinition } [,...] ) ]
[ ENGINE tableEngineName ]
[ WITH tableEngineParamName [,...] ]
[ NOT PERSISTENT ] [ TRANSACTIONAL ]
[ AS ( query ) [ WITH [ NO ] DATA ] ]
193 of 428
The ENGINE option is only required when custom table implementations
are used. The table engine class must implement the interface
org.h2.api.TableEngine. Any table engine parameters are passed down in
the tableEngineParams field of the CreateTableData object.
Either ENGINE, or WITH (table engine params), or both may be specified. If
ENGINE is not specified in CREATE TABLE, then the engine specified by
DEFAULT_TABLE_ENGINE option of database params is used.
Tables with the NOT PERSISTENT modifier are kept fully in memory, and
all rows are lost when the database is closed.
The column definitions are optional if a query is specified. In that case the
column list of the query is used. If the query is specified its results are
inserted into created table unless WITH NO DATA is specified.
This command commits an open transaction, except when using
TRANSACTIONAL (only supported for temporary tables).
Example:
CREATE TABLE TEST(ID INT PRIMARY KEY, NAME VARCHAR(255))
CREATE TRIGGER
CREATE TRIGGER [ IF NOT EXISTS ] [schemaName.]triggerName
{ BEFORE | AFTER | INSTEAD OF }
{ INSERT | UPDATE | DELETE | { SELECT | ROLLBACK } }
[,...] ON [schemaName.]tableName [ FOR EACH { ROW | STATEMENT } ]
[ QUEUE int ] [ NOWAIT ]
{ CALL triggeredClassNameString | AS sourceCodeString }
194 of 428
javascript (included in every JRE) and ruby (with JRuby) are supported. In
that case the source must begin respectively with //javascript or #ruby.
BEFORE triggers are called after data conversion is made, default values
are set, null and length constraint checks have been made; but before
other constraints have been checked. If there are multiple triggers, the
order in which they are called is undefined.
ROLLBACK can be specified in combination with INSERT, UPDATE, and
DELETE. Only row based AFTER trigger can be called on ROLLBACK.
Exceptions that occur within such triggers are ignored. As the operations
that occur within a trigger are part of the transaction, ROLLBACK triggers
are only required if an operation communicates outside of the database.
INSTEAD OF triggers are implicitly row based and behave like BEFORE
triggers. Only the first such trigger is called. Such triggers on views are
supported. They can be used to make views updatable. These triggers on
INSERT and UPDATE must update the passed new row to values that were
actually inserted by the trigger; they are used for FINAL TABLE and for
retrieval of generated keys.
A BEFORE SELECT trigger is fired just before the database engine tries to
read from the table. The trigger can be used to update a table on demand.
The trigger is called with both 'old' and 'new' set to null.
The MERGE statement will call both INSERT and UPDATE triggers. Not
supported are SELECT triggers with the option FOR EACH ROW, and AFTER
SELECT triggers.
Committing or rolling back a transaction within a trigger is not allowed,
except for SELECT triggers.
By default a trigger is called once for each statement, without the old and
new rows. FOR EACH ROW triggers are called once for each inserted,
updated, or deleted row.
QUEUE is implemented for syntax compatibility with HSQL and has no
effect.
The trigger need to be created in the same schema as the table. The
schema name does not need to be specified when creating the trigger.
This command commits an open transaction in this connection.
Example:
195 of 428
CREATE TRIGGER TRIG_INS BEFORE INSERT ON TEST FOR EACH ROW CALL
'MyTrigger';
CREATE TRIGGER TRIG_SRC BEFORE INSERT ON TEST AS
'org.h2.api.Trigger create() { return new
MyTrigger("constructorParam"); }';
CREATE TRIGGER TRIG_JS BEFORE INSERT ON TEST AS '//javascript
return new Packages.MyTrigger("constructorParam");';
CREATE TRIGGER TRIG_RUBY BEFORE INSERT ON TEST AS '#ruby
Java::MyPackage::MyTrigger.new("constructorParam")';
CREATE USER
CREATE USER [ IF NOT EXISTS ] newUserName
{ PASSWORD string | SALT bytes HASH bytes } [ ADMIN ]
CREATE VIEW
CREATE [ OR REPLACE ] [ FORCE ]
VIEW [ IF NOT EXISTS ] [schemaName.]viewName
[ ( columnName [,...] ) ] AS query
Creates a new view. If the force option is used, then the view is created
even if the underlying table(s) don't exist. Schema owner rights are
required to execute this command.
If the OR REPLACE clause is used an existing view will be replaced, and
any dependent views will not need to be recreated. If dependent views will
become invalid as a result of the change an error will be generated, but
this error can be ignored if the FORCE clause is also used.
Views are not updatable except when using 'instead of' triggers.
196 of 428
This command commits an open transaction in this connection.
Example:
CREATE VIEW TEST_VIEW AS SELECT * FROM TEST WHERE ID < 100
DROP AGGREGATE
DROP AGGREGATE [ IF EXISTS ] aggregateName
DROP ALIAS
DROP ALIAS [ IF EXISTS ] [schemaName.]aliasName
197 of 428
DROP CONSTANT
DROP CONSTANT [ IF EXISTS ] [schemaName.]constantName
DROP DOMAIN
DROP DOMAIN [ IF EXISTS ] [schemaName.]domainName [ RESTRICT |
CASCADE ]
Drops a data type (domain). Schema owner rights are required to execute
this command.
The command will fail if it is referenced by a column or another domain
(the default). Column descriptors are replaced with original definition of
specified domain if the CASCADE clause is used. Default and on update
expressions are copied into domains and columns that use this domain
and don't have own expressions. Domain constraints are copied into
domains that use this domain and to columns (as check constraints) that
use this domain. This command commits an open transaction in this
connection.
Example:
DROP DOMAIN EMAIL
DROP INDEX
DROP INDEX [ IF EXISTS ] [schemaName.]indexName
DROP ROLE
DROP ROLE [ IF EXISTS ] roleName
198 of 428
Drops a role. Admin rights are required to execute this command. This
command commits an open transaction in this connection.
Example:
DROP ROLE READONLY
DROP SCHEMA
DROP SCHEMA [ IF EXISTS ] schemaName [ RESTRICT | CASCADE ]
DROP SEQUENCE
DROP SEQUENCE [ IF EXISTS ] [schemaName.]sequenceName
DROP TABLE
DROP TABLE [ IF EXISTS ] [schemaName.]tableName [,...]
[ RESTRICT | CASCADE ]
199 of 428
DROP TRIGGER
DROP TRIGGER [ IF EXISTS ] [schemaName.]triggerName
DROP USER
DROP USER [ IF EXISTS ] userName
Drops a user. The current user cannot be dropped. For compatibility, only
unquoted or uppercase user names are allowed.
Admin rights are required to execute this command. This command
commits an open transaction in this connection.
Example:
DROP USER TOM
DROP VIEW
DROP VIEW [ IF EXISTS ] [schemaName.]viewName [ RESTRICT |
CASCADE ]
Drops an existing view. Schema owner rights are required to execute this
command. All dependent views are dropped as well if the CASCADE clause
is used (the default). The command will fail if dependent views exist and
the RESTRICT clause is used. This command commits an open transaction
in this connection.
Example:
DROP VIEW TEST_VIEW
TRUNCATE TABLE
TRUNCATE TABLE [schemaName.]tableName [ [ CONTINUE | RESTART ]
IDENTITY ]
200 of 428
Removes all rows from a table. Unlike DELETE FROM without where
clause, this command can not be rolled back. This command is faster than
DELETE without where clause. Only regular data tables without foreign
key constraints can be truncated (except if referential integrity is disabled
for this database or for this table). Linked tables can't be truncated. If
RESTART IDENTITY is specified next values for identity columns are
restarted.
This command commits an open transaction in this connection.
Example:
TRUNCATE TABLE TEST
Commands (Other)
CHECKPOINT
CHECKPOINT
CHECKPOINT SYNC
CHECKPOINT SYNC
Flushes the data to disk and forces all system buffers be written to the
underlying device.
Admin rights are required to execute this command.
Example:
CHECKPOINT SYNC
COMMIT
COMMIT [ WORK ]
Commits a transaction.
201 of 428
Example:
COMMIT
COMMIT TRANSACTION
COMMIT TRANSACTION transactionName
GRANT RIGHT
GRANT { { SELECT | INSERT | UPDATE | DELETE } [,..] | ALL
[ PRIVILEGES ] } ON
{ { SCHEMA schemaName } | { [ TABLE ] [schemaName.]tableName [,...]
}}
TO { PUBLIC | userName | roleName }
202 of 428
GRANT ALTER ANY SCHEMA TO Bob
GRANT ROLE
GRANT { roleName [,...] } TO { PUBLIC | userName | roleName }
HELP
HELP [ anything [...] ]
PREPARE COMMIT
PREPARE COMMIT newTransactionName
REVOKE RIGHT
REVOKE { { SELECT | INSERT | UPDATE | DELETE } [,..] | ALL [ PRIVILEGES
] } ON
{ { SCHEMA schemaName } | { [ TABLE ] [schemaName.]tableName [,...]
}}
FROM { PUBLIC | userName | roleName }
REVOKE ROLE
REVOKE { roleName [,...] } FROM { PUBLIC | userName | roleName }
ROLLBACK
ROLLBACK [ WORK ] [ TO SAVEPOINT savepointName ]
ROLLBACK TRANSACTION
ROLLBACK TRANSACTION transactionName
204 of 428
Admin rights are required to execute this command. This command is part
of the 2-phase-commit protocol.
Example:
ROLLBACK TRANSACTION XID_TEST
SAVEPOINT
SAVEPOINT savepointName
Create a new savepoint. See also ROLLBACK. Savepoints are only valid
until the transaction is committed or rolled back.
Example:
SAVEPOINT HALF_DONE
SET @
SET @variableName [ = ] expression
SET ALLOW_LITERALS
SET ALLOW_LITERALS { NONE | ALL | NUMBERS }
This setting can help solve the SQL injection problem. By default, text and
number literals are allowed in SQL statements. However, this enables SQL
injection if the application dynamically builds SQL statements. SQL
injection is not possible if user data is set using parameters ('?').
NONE means literals of any kind are not allowed, only parameters and
constants are allowed. NUMBERS mean only numerical and boolean
literals are allowed. ALL means all literals are allowed (default).
See also CREATE CONSTANT.
205 of 428
Admin rights are required to execute this command, as it affects all
connections. This command commits an open transaction in this
connection. This setting is persistent. This setting can be appended to the
database URL: jdbc:h2:./test;ALLOW_LITERALS=NONE
Example:
SET ALLOW_LITERALS NONE
SET AUTOCOMMIT
SET AUTOCOMMIT { TRUE | ON | FALSE | OFF }
SET CACHE_SIZE
SET CACHE_SIZE int
Sets the size of the cache in KB (each KB being 1024 bytes) for the current
database. The default is 65536 per available GB of RAM, i.e. 64 MB per
GB. The value is rounded to the next higher power of two. Depending on
the virtual machine, the actual memory required may be higher.
This setting is persistent and affects all connections as there is only one
cache per database. Using a very small value (specially 0) will reduce
performance a lot. This setting only affects the database engine (the
server in a client/server environment; in embedded mode, the database
engine is in the same process as the application). It has no effect for in-
memory databases.
Admin rights are required to execute this command, as it affects all
connections. This command commits an open transaction in this
connection. This setting is persistent. This setting can be appended to the
database URL: jdbc:h2:./test;CACHE_SIZE=8192
206 of 428
Example:
SET CACHE_SIZE 8192
SET CLUSTER
SET CLUSTER serverListString
SET BUILTIN_ALIAS_OVERRIDE
SET BUILTIN_ALIAS_OVERRIDE { TRUE | FALSE }
Allows the overriding of the builtin system date/time functions for unit
testing purposes.
Admin rights are required to execute this command. This command
commits an open transaction in this connection.
Example:
SET BUILTIN_ALIAS_OVERRIDE TRUE
SET CATALOG
SET CATALOG { catalogString | { catalogName } }
This command has no effect if the specified name matches the name of
the database, otherwise it throws an exception.
This command does not commit a transaction.
Example:
207 of 428
SET CATALOG 'DB'
SET CATALOG DB_NAME
SET COLLATION
SET [ DATABASE ] COLLATION
{ OFF | collationName
[ STRENGTH { PRIMARY | SECONDARY | TERTIARY | IDENTICAL } ] }
Sets the collation used for comparing strings. This command can only be
executed if there are no tables defined. See java.text.Collator for details
about the supported collations and the STRENGTH (PRIMARY is usually
case- and umlaut-insensitive; SECONDARY is case-insensitive but umlaut-
sensitive; TERTIARY is both case- and umlaut-sensitive; IDENTICAL is
sensitive to all differences and only affects ordering).
The ICU4J collator is used if it is in the classpath. It is also used if the
collation name starts with ICU4J_ (in that case, the ICU4J must be in the
classpath, otherwise an exception is thrown). The default collator is used if
the collation name starts with DEFAULT_ (even if ICU4J is in the classpath).
The charset collator is used if the collation name starts with CHARSET_
(e.g. CHARSET_CP500). This collator sorts strings according to the binary
representation in the given charset.
Admin rights are required to execute this command. This command
commits an open transaction in this connection. This setting is persistent.
This setting can be appended to the database URL:
jdbc:h2:./test;COLLATION='ENGLISH'
Example:
SET COLLATION ENGLISH
SET COLLATION CHARSET_CP500
SET DATABASE_EVENT_LISTENER
SET DATABASE_EVENT_LISTENER classNameString
Sets the event listener class. An empty string ('') means no listener should
be used. This setting is not persistent.
Admin rights are required to execute this command, except if it is set
when opening the database (in this case it is reset just after opening the
208 of 428
database). This setting can be appended to the database URL:
jdbc:h2:./test;DATABASE_EVENT_LISTENER='sample.MyListener'
Example:
SET DATABASE_EVENT_LISTENER 'sample.MyListener'
SET DB_CLOSE_DELAY
SET DB_CLOSE_DELAY int
Sets the delay for closing a database if all connections are closed. The
value -1 means the database is never closed until the close delay is set to
some other value or SHUTDOWN is called. The value 0 means no delay
(default; the database is closed if the last connection to it is closed).
Values 1 and larger mean the number of seconds the database is left open
after closing the last connection.
If the application exits normally or System.exit is called, the database is
closed immediately, even if a delay is set.
Admin rights are required to execute this command, as it affects all
connections. This command commits an open transaction in this
connection. This setting is persistent. This setting can be appended to the
database URL: jdbc:h2:./test;DB_CLOSE_DELAY=-1
Example:
SET DB_CLOSE_DELAY -1
SET DEFAULT_LOCK_TIMEOUT
SET DEFAULT LOCK_TIMEOUT int
Sets the default lock timeout (in milliseconds) in this database that is used
for the new sessions. The default value for this setting is 1000 (one
second).
Admin rights are required to execute this command, as it affects all
connections. This command commits an open transaction in this
connection. This setting is persistent.
Example:
SET DEFAULT_LOCK_TIMEOUT 5000
209 of 428
SET DEFAULT_NULL_ORDERING
SET DEFAULT_NULL_ORDERING { LOW | HIGH | FIRST | LAST }
Changes the default ordering of NULL values. This setting affects new
indexes without explicit NULLS FIRST or NULLS LAST columns, and
ordering clauses of other commands without explicit null ordering. This
setting doesn't affect ordering of NULL values inside ARRAY or ROW
values (ARRAY[NULL] is always considered as smaller than ARRAY[1]
during sorting).
LOW is the default one, NULL values are considered as smaller than other
values during sorting.
With HIGH default ordering NULL values are considered as larger than
other values during sorting.
With FIRST default ordering NULL values are sorted before other values,
no matter if ascending or descending order is used.
WITH LAST default ordering NULL values are sorted after other values, no
matter if ascending or descending order is used.
This setting is not persistent, but indexes are persisted with explicit NULLS
FIRST or NULLS LAST ordering and aren't affected by changes in this
setting. Admin rights are required to execute this command, as it affects
all connections. This command commits an open transaction in this
connection. This setting can be appended to the database URL:
jdbc:h2:./test;DEFAULT_NULL_ORDERING=HIGH
Example:
SET DEFAULT_NULL_ORDERING HIGH
SET DEFAULT_TABLE_TYPE
SET DEFAULT_TABLE_TYPE { MEMORY | CACHED }
Sets the default table storage type that is used when creating new tables.
Memory tables are kept fully in the main memory (including indexes),
however the data is still stored in the database file. The size of memory
tables is limited by the memory. The default is CACHED.
Admin rights are required to execute this command, as it affects all
connections. This command commits an open transaction in this
210 of 428
connection. This setting is persistent. It has no effect for in-memory
databases.
Example:
SET DEFAULT_TABLE_TYPE MEMORY
SET EXCLUSIVE
SET EXCLUSIVE { 0 | 1 | 2 }
Switched the database to exclusive mode (1, 2) and back to normal mode
(0).
In exclusive mode, new connections are rejected, and operations by other
connections are paused until the exclusive mode is disabled. When using
the value 1, existing connections stay open. When using the value 2, all
existing connections are closed (and current transactions are rolled back)
except the connection that executes SET EXCLUSIVE. Only the connection
that set the exclusive mode can disable it. When the connection is closed,
it is automatically disabled.
Admin rights are required to execute this command. This command
commits an open transaction in this connection.
Example:
SET EXCLUSIVE 1
SET IGNORECASE
SET IGNORECASE { TRUE | FALSE }
211 of 428
Example:
SET IGNORECASE TRUE
SET IGNORE_CATALOGS
SET IGNORE_CATALOGS { TRUE | FALSE }
SET JAVA_OBJECT_SERIALIZER
SET JAVA_OBJECT_SERIALIZER { null | className }
Sets the object used to serialize and deserialize java objects being stored
in column of type OTHER. The serializer class must be public and
implement org.h2.api.JavaObjectSerializer. Inner classes are not
supported. The class must be available in the classpath of the database
engine (when using the server mode, it must be both in the classpath of
the server and the client). This command can only be executed if there
are no tables defined.
Admin rights are required to execute this command. This command
commits an open transaction in this connection. This setting is persistent.
This setting can be appended to the database URL:
jdbc:h2:./test;JAVA_OBJECT_SERIALIZER='com.acme.SerializerClassName'
Example:
SET JAVA_OBJECT_SERIALIZER 'com.acme.SerializerClassName'
SET LAZY_QUERY_EXECUTION
SET LAZY_QUERY_EXECUTION int
212 of 428
Sets the lazy query execution mode. The values 0, 1 are supported.
If true, then large results are retrieved in chunks.
Note that not all queries support this feature, queries which do not are
processed normally.
This command does not commit a transaction, and rollback does not
affect it. This setting can be appended to the database URL:
jdbc:h2:./test;LAZY_QUERY_EXECUTION=1
Example:
SET LAZY_QUERY_EXECUTION 1
SET LOCK_MODE
SET LOCK_MODE int
Sets the lock mode. The values 0, 1, 2, and 3 are supported. The default is
3. This setting affects all connections.
The value 0 means no locking (should only be used for testing). Please
note that using SET LOCK_MODE 0 while at the same time using multiple
connections may result in inconsistent transactions.
The value 3 means row-level locking for write operations.
The values 1 and 2 have the same effect as 3.
Admin rights are required to execute this command, as it affects all
connections. This command commits an open transaction in this
connection. This setting is persistent. This setting can be appended to the
database URL: jdbc:h2:./test;LOCK_MODE=0
Example:
SET LOCK_MODE 0
SET LOCK_TIMEOUT
SET LOCK_TIMEOUT int
Sets the lock timeout (in milliseconds) for the current session. The default
value for this setting is 1000 (one second).
213 of 428
This command does not commit a transaction, and rollback does not
affect it. This setting can be appended to the database URL:
jdbc:h2:./test;LOCK_TIMEOUT=10000
Example:
SET LOCK_TIMEOUT 1000
SET MAX_LENGTH_INPLACE_LOB
SET MAX_LENGTH_INPLACE_LOB int
SET MAX_LOG_SIZE
SET MAX_LOG_SIZE int
Sets the maximum size of the transaction log, in megabytes. If the log is
larger, and if there is no open transaction, the transaction log is truncated.
If there is an open transaction, the transaction log will continue to grow
however. The default max size is 16 MB. This setting has no effect for in-
memory databases.
Admin rights are required to execute this command, as it affects all
connections. This command commits an open transaction in this
connection. This setting is persistent.
Example:
SET MAX_LOG_SIZE 2
SET MAX_MEMORY_ROWS
SET MAX_MEMORY_ROWS int
214 of 428
The maximum number of rows in a result set that are kept in-memory. If
more rows are read, then the rows are buffered to disk. The default is
40000 per GB of available RAM.
Admin rights are required to execute this command, as it affects all
connections. This command commits an open transaction in this
connection. This setting is persistent. It has no effect for in-memory
databases.
Example:
SET MAX_MEMORY_ROWS 1000
SET MAX_MEMORY_UNDO
SET MAX_MEMORY_UNDO int
The maximum number of undo records per a session that are kept in-
memory. If a transaction is larger, the records are buffered to disk. The
default value is 50000. Changes to tables without a primary key can not
be buffered to disk. This setting is not supported when using multi-version
concurrency.
Admin rights are required to execute this command, as it affects all
connections. This command commits an open transaction in this
connection. This setting is persistent. It has no effect for in-memory
databases.
Example:
SET MAX_MEMORY_UNDO 1000
SET MAX_OPERATION_MEMORY
SET MAX_OPERATION_MEMORY int
Sets the maximum memory used for large operations (delete and insert),
in bytes. Operations that use more memory are buffered to disk, slowing
down the operation. The default max size is 100000. 0 means no limit.
This setting is not persistent. Admin rights are required to execute this
command, as it affects all connections. It has no effect for in-memory
databases. This setting can be appended to the database URL:
jdbc:h2:./test;MAX_OPERATION_MEMORY=10000
215 of 428
Example:
SET MAX_OPERATION_MEMORY 0
SET MODE
SET MODE { REGULAR | STRICT | LEGACY | DB2 | DERBY | HSQLDB |
MSSQLSERVER | MYSQL | ORACLE | POSTGRESQL }
SET NON_KEYWORDS
SET NON_KEYWORDS [ name [,...] ]
Converts the specified tokens from keywords to plain identifiers for the
current session. This setting may break some commands and should be
used with caution and only when necessary. Use quoted identifiers instead
of this setting if possible.
This command does not commit a transaction, and rollback does not
affect it. This setting can be appended to the database URL:
jdbc:h2:./test;NON_KEYWORDS=KEY,VALUE
Example:
SET NON_KEYWORDS KEY, VALUE
SET OPTIMIZE_REUSE_RESULTS
SET OPTIMIZE_REUSE_RESULTS { 0 | 1 }
216 of 428
Admin rights are required to execute this command, as it affects all
connections. This command commits an open transaction in this
connection. This setting can be appended to the database URL:
jdbc:h2:./test;OPTIMIZE_REUSE_RESULTS=0
Example:
SET OPTIMIZE_REUSE_RESULTS 0
SET PASSWORD
SET PASSWORD string
Changes the password of the current user. The password must be in single
quotes. It is case sensitive and can contain spaces.
This command commits an open transaction in this connection.
Example:
SET PASSWORD 'abcstzri!.5'
SET QUERY_STATISTICS
SET QUERY_STATISTICS { TRUE | FALSE }
Disabled or enables query statistics gathering for the whole database. The
statistics are reflected in the INFORMATION_SCHEMA.QUERY_STATISTICS
meta-table.
This setting is not persistent. This command commits an open transaction
in this connection. Admin rights are required to execute this command, as
it affects all connections.
Example:
SET QUERY_STATISTICS FALSE
SET QUERY_STATISTICS_MAX_ENTRIES
SET QUERY_STATISTICS int
217 of 428
This setting is not persistent. This command commits an open transaction
in this connection. Admin rights are required to execute this command, as
it affects all connections.
Example:
SET QUERY_STATISTICS_MAX_ENTRIES 500
SET QUERY_TIMEOUT
SET QUERY_TIMEOUT int
Set the query timeout of the current session to the given value. The
timeout is in milliseconds. All kinds of statements will throw an exception
if they take longer than the given value. The default timeout is 0, meaning
no timeout.
This command does not commit a transaction, and rollback does not
affect it.
Example:
SET QUERY_TIMEOUT 10000
SET REFERENTIAL_INTEGRITY
SET REFERENTIAL_INTEGRITY { TRUE | FALSE }
SET RETENTION_TIME
SET RETENTION_TIME int
Sets the password salt and hash for the current user. The password must
be in single quotes. It is case sensitive and can contain spaces.
This command commits an open transaction in this connection.
Example:
SET SALT '00' HASH '1122'
SET SCHEMA
SET SCHEMA { schemaString | { schemaName } }
219 of 428
SET SCHEMA_SEARCH_PATH
SET SCHEMA_SEARCH_PATH schemaName [,...]
Changes the schema search path of the current connection. The default
schema is used in statements where no schema is set explicitly. The
default schema for new connections is PUBLIC.
This command does not commit a transaction, and rollback does not
affect it. This setting can be appended to the database URL:
jdbc:h2:./test;SCHEMA_SEARCH_PATH=ABC,DEF
Example:
SET SCHEMA_SEARCH_PATH INFORMATION_SCHEMA, PUBLIC
Changes the transaction isolation level of the current session. The actual
support of isolation levels depends on the database engine.
This command commits an open transaction in this session.
Example:
SET SESSION CHARACTERISTICS AS TRANSACTION ISOLATION LEVEL
SERIALIZABLE
SET THROTTLE
SET THROTTLE int
Sets the throttle for the current connection. The value is the number of
milliseconds delay after each 50 ms. The default value is 0 (throttling
disabled).
This command does not commit a transaction, and rollback does not
affect it. This setting can be appended to the database URL:
jdbc:h2:./test;THROTTLE=50
Example:
SET THROTTLE 200
220 of 428
SET TIME ZONE
SET TIME ZONE { LOCAL | intervalHourToMinute | { intervalHourToSecond
| string } }
SET TRACE_LEVEL
SET { TRACE_LEVEL_FILE | TRACE_LEVEL_SYSTEM_OUT } int
Sets the trace level for file the file or system out stream. Levels are:
0=off, 1=error, 2=info, 3=debug. The default level is 1 for file and 0 for
system out. To use SLF4J, append ;TRACE_LEVEL_FILE=4 to the database
URL when opening the database.
This setting is not persistent. Admin rights are required to execute this
command, as it affects all connections. This command does not commit a
transaction, and rollback does not affect it. This setting can be appended
to the database URL: jdbc:h2:./test;TRACE_LEVEL_SYSTEM_OUT=3
Example:
SET TRACE_LEVEL_SYSTEM_OUT 3
SET TRACE_MAX_FILE_SIZE
SET TRACE_MAX_FILE_SIZE int
221 of 428
Sets the maximum trace file size. If the file exceeds the limit, the file is
renamed to .old and a new file is created. If another .old file exists, it is
deleted. The default max size is 16 MB.
This setting is persistent. Admin rights are required to execute this
command, as it affects all connections. This command commits an open
transaction in this connection. This setting can be appended to the
database URL: jdbc:h2:./test;TRACE_MAX_FILE_SIZE=3
Example:
SET TRACE_MAX_FILE_SIZE 10
SET TRUNCATE_LARGE_LENGTH
SET TRUNCATE_LARGE_LENGTH { TRUE | FALSE }
SET VARIABLE_BINARY
SET VARIABLE_BINARY { TRUE | FALSE }
SET WRITE_DELAY
SET WRITE_DELAY int
Set the maximum delay between a commit and flushing the log, in
milliseconds. This setting is persistent. The default is 500 ms.
222 of 428
Admin rights are required to execute this command, as it affects all
connections. This command commits an open transaction in this
connection. This setting can be appended to the database URL:
jdbc:h2:./test;WRITE_DELAY=0
Example:
SET WRITE_DELAY 2000
SHUTDOWN
SHUTDOWN [ IMMEDIATELY | COMPACT | DEFRAG ]
This statement closes all open connections to the database and closes the
database. This command is usually not required, as the database is closed
automatically when the last connection to it is closed.
If no option is used, then the database is closed normally. All connections
are closed, open transactions are rolled back.
SHUTDOWN COMPACT fully compacts the database (re-creating the
database may further reduce the database size). If the database is closed
normally (using SHUTDOWN or by closing all connections), then the
database is also compacted, but only for at most the time defined by the
database setting h2.maxCompactTime in milliseconds (see there).
SHUTDOWN IMMEDIATELY closes the database files without any cleanup
and without compacting.
SHUTDOWN DEFRAG is currently equivalent to COMPACT.
Admin rights are required to execute this command.
Example:
SHUTDOWN COMPACT
223 of 428
Functions
Index
Numeric Functions
ABS
ACOS
ASIN
ATAN
COS
COSH
COT
SIN
SINH
TAN
TANH
ATAN2
BITAND
BITOR
BITXOR
BITNOT
BITNAND
BITNOR
BITXNOR
BITGET
BITCOUNT
LSHIFT
RSHIFT
ULSHIFT
URSHIFT
ROTATELEFT
ROTATERIGHT
MOD
CEIL
DEGREES
EXP
FLOOR
224 of 428
LN
LOG
LOG10
ORA_HASH
RADIANS
SQRT
PI
POWER
RAND
RANDOM_UUID
ROUND
SECURE_RAND
SIGN
ENCRYPT
DECRYPT
HASH
TRUNC
COMPRESS
EXPAND
ZERO
String Functions
ASCII
BIT_LENGTH
CHAR_LENGTH
OCTET_LENGTH
CHAR
CONCAT
CONCAT_WS
DIFFERENCE
HEXTORAW
RAWTOHEX
INSERT Function
LOWER
UPPER
LEFT
RIGHT
LOCATE
225 of 428
LPAD
RPAD
LTRIM
RTRIM
TRIM
REGEXP_REPLACE
REGEXP_LIKE
REGEXP_SUBSTR
REPEAT
REPLACE
SOUNDEX
SPACE
STRINGDECODE
STRINGENCODE
STRINGTOUTF8
SUBSTRING
UTF8TOSTRING
QUOTE_IDENT
XMLATTR
XMLNODE
XMLCOMMENT
XMLCDATA
XMLSTARTDOC
XMLTEXT
TO_CHAR
TRANSLATE
System Functions
ABORT_SESSION
ARRAY_GET
CARDINALITY
ARRAY_CONTAINS
ARRAY_CAT
ARRAY_APPEND
ARRAY_MAX_CARDINALITY
TRIM_ARRAY
ARRAY_SLICE
AUTOCOMMIT
CANCEL_SESSION
CASEWHEN Function
COALESCE
CONVERT
CURRVAL
CSVWRITE
CURRENT_SCHEMA
CURRENT_CATALOG
DATABASE_PATH
DATA_TYPE_SQL
227 of 428
DB_OBJECT_ID
DB_OBJECT_SQL
DECODE
DISK_SPACE_USED
SIGNAL
ESTIMATED_ENVELOPE
FILE_READ
FILE_WRITE
GREATEST
LEAST
LOCK_MODE
LOCK_TIMEOUT
MEMORY_FREE
MEMORY_USED
NEXTVAL
NULLIF
NVL2
READONLY
ROWNUM
SESSION_ID
SET
TRANSACTION_ID
TRUNCATE_VALUE
CURRENT_PATH
CURRENT_ROLE
CURRENT_USER
H2VERSION
JSON Functions
JSON_OBJECT
JSON_ARRAY
Table Functions
CSVREAD
LINK_SCHEMA
TABLE
UNNEST
228 of 428
Details
Non-standard syntax is marked in green. Compatibility-only non-standard
syntax is marked in red, don't use it unless you need it for compatibility
with other databases or old versions of H2.
Numeric Functions
ABS
ABS( { numeric | interval } )
ACOS
ACOS(numeric)
Calculate the arc cosine. See also Java Math.acos. This method returns a
double.
Example:
ACOS(D)
ASIN
ASIN(numeric)
Calculate the arc sine. See also Java Math.asin. This method returns a
double.
229 of 428
Example:
ASIN(D)
ATAN
ATAN(numeric)
Calculate the arc tangent. See also Java Math.atan. This method returns a
double.
Example:
ATAN(D)
COS
COS(numeric)
Calculate the trigonometric cosine. See also Java Math.cos. This method
returns a double.
Example:
COS(ANGLE)
COSH
COSH(numeric)
Calculate the hyperbolic cosine. See also Java Math.cosh. This method
returns a double.
Example:
COSH(X)
COT
COT(numeric)
230 of 428
SIN
SIN(numeric)
Calculate the trigonometric sine. See also Java Math.sin. This method
returns a double.
Example:
SIN(ANGLE)
SINH
SINH(numeric)
Calculate the hyperbolic sine. See also Java Math.sinh. This method
returns a double.
Example:
SINH(ANGLE)
TAN
TAN(numeric)
Calculate the trigonometric tangent. See also Java Math.tan. This method
returns a double.
Example:
TAN(ANGLE)
TANH
TANH(numeric)
Calculate the hyperbolic tangent. See also Java Math.tanh. This method
returns a double.
Example:
TANH(X)
ATAN2
ATAN2(numeric, numeric)
231 of 428
Calculate the angle when converting the rectangular coordinates to polar
coordinates. See also Java Math.atan2. This method returns a double.
Example:
ATAN2(X, Y)
BITAND
BITAND(expression, expression)
BITOR
BITOR(expression, expression)
BITXOR
BITXOR(expression, expression)
BITNAND
BITNAND(expression, expression)
BITNOR
BITNOR(expression, expression)
BITXNOR
BITXNOR(expression, expression)
233 of 428
The bitwise XNOR operation equivalent to BITNOT(BITXOR(expression,
expression)). Arguments should have TINYINT, SMALLINT, INTEGER,
BIGINT, BINARY, or BINARY VARYING data type. This function returns result
of the same data type.
For aggregate function see BIT_XNOR_AGG.
Example:
BITXNOR(A, B)
BITGET
BITGET(expression, long)
Returns true if and only if the first argument has a bit set in the position
specified by the second parameter. The first argument should have
TINYINT, SMALLINT, INTEGER, BIGINT, BINARY, or BINARY VARYING data
type. This method returns a boolean. The second argument is zero-
indexed; the least significant bit has position 0.
Example:
BITGET(A, 1)
BITCOUNT
BITCOUNT(expression)
Returns count of set bits in the specified value. Value should have
TINYINT, SMALLINT, INTEGER, BIGINT, BINARY, or BINARY VARYING data
type. This method returns a long.
Example:
BITCOUNT(A)
LSHIFT
LSHIFT(expression, long)
The bitwise signed left shift operation. Shifts the first argument by the
number of bits given by the second argument. Argument should have
TINYINT, SMALLINT, INTEGER, BIGINT, BINARY, or BINARY VARYING data
type. This function returns result of the same data type.
234 of 428
If number of bits is negative, a signed right shift is performed instead. For
numeric values a sign bit is used for left-padding (with negative offset). If
number of bits is equal to or larger than number of bits in value all bits are
pushed out from the value. For binary string arguments signed and
unsigned shifts return the same results.
Example:
LSHIFT(A, B)
RSHIFT
RSHIFT(expression, long)
The bitwise signed right shift operation. Shifts the first argument by the
number of bits given by the second argument. Argument should have
TINYINT, SMALLINT, INTEGER, BIGINT, BINARY, or BINARY VARYING data
type. This function returns result of the same data type.
If number of bits is negative, a signed left shift is performed instead. For
numeric values a sign bit is used for left-padding (with positive offset). If
number of bits is equal to or larger than number of bits in value all bits are
pushed out from the value. For binary string arguments signed and
unsigned shifts return the same results.
Example:
RSHIFT(A, B)
ULSHIFT
ULSHIFT(expression, long)
The bitwise unsigned left shift operation. Shifts the first argument by the
number of bits given by the second argument. Argument should have
TINYINT, SMALLINT, INTEGER, BIGINT, BINARY, or BINARY VARYING data
type. This function returns result of the same data type.
If number of bits is negative, an unsigned right shift is performed instead.
If number of bits is equal to or larger than number of bits in value all bits
are pushed out from the value. For binary string arguments signed and
unsigned shifts return the same results.
Example:
235 of 428
ULSHIFT(A, B)
URSHIFT
URSHIFT(expression, long)
The bitwise unsigned right shift operation. Shifts the first argument by the
number of bits given by the second argument. Argument should have
TINYINT, SMALLINT, INTEGER, BIGINT, BINARY, or BINARY VARYING data
type. This function returns result of the same data type.
If number of bits is negative, an unsigned left shift is performed instead. If
number of bits is equal to or larger than number of bits in value all bits are
pushed out from the value. For binary string arguments signed and
unsigned shifts return the same results.
Example:
URSHIFT(A, B)
ROTATELEFT
ROTATELEFT(expression, long)
The bitwise left rotation operation. Rotates the first argument by the
number of bits given by the second argument. Argument should have
TINYINT, SMALLINT, INTEGER, BIGINT, BINARY, or BINARY VARYING data
type. This function returns result of the same data type.
Example:
ROTATELEFT(A, B)
ROTATERIGHT
ROTATERIGHT(expression, long)
The bitwise right rotation operation. Rotates the first argument by the
number of bits given by the second argument. Argument should have
TINYINT, SMALLINT, INTEGER, BIGINT, BINARY, or BINARY VARYING data
type. This function returns result of the same data type.
Example:
ROTATERIGHT(A, B)
236 of 428
MOD
MOD(dividendNumeric, divisorNumeric)
CEIL
{ CEIL | CEILING } (numeric)
Returns the smallest integer value that is greater than or equal to the
argument. This method returns value of the same type as argument, but
with scale set to 0 and adjusted precision, if applicable.
Example:
CEIL(A)
DEGREES
DEGREES(numeric)
EXP
EXP(numeric)
237 of 428
FLOOR
FLOOR(numeric)
Returns the largest integer value that is less than or equal to the
argument. This method returns value of the same type as argument, but
with scale set to 0 and adjusted precision, if applicable.
Example:
FLOOR(A)
LN
LN(numeric)
LOG
LOG({baseNumeric, numeric | {numeric}})
LOG10
LOG10(numeric)
ORA_HASH
ORA_HASH(expression [, bucketLong [, seedLong]])
RADIANS
RADIANS(numeric)
SQRT
SQRT(numeric)
PI
PI()
POWER
POWER(numeric, numeric)
RAND
{ RAND | RANDOM } ( [ int ] )
Calling the function without parameter returns the next a pseudo random
number. Calling it with an parameter seeds the session's random number
generator. This method returns a double between 0 (including) and 1
(excluding).
Example:
RAND()
RANDOM_UUID
{ RANDOM_UUID | UUID } ()
ROUND
ROUND(numeric [, digitsInt])
240 of 428
Rounds to a number of fractional digits. This method returns value of the
same type as argument, but with adjusted precision and scale, if
applicable.
Example:
ROUND(N, 2)
SECURE_RAND
SECURE_RAND(int)
SIGN
SIGN( { numeric | interval } )
ENCRYPT
ENCRYPT(algorithmString, keyBytes, dataBytes)
Encrypts data using a key. The supported algorithm is AES. The block size
is 16 bytes. This method returns bytes.
Example:
CALL ENCRYPT('AES', '00', STRINGTOUTF8('Test'))
DECRYPT
DECRYPT(algorithmString, keyBytes, dataBytes)
Decrypts data using a key. The supported algorithm is AES. The block size
is 16 bytes. This method returns bytes.
Example:
241 of 428
CALL TRIM(CHAR(0) FROM UTF8TOSTRING(
DECRYPT('AES', '00', '3fabb4de8f1ee2e97d7793bab2db1116')))
HASH
HASH(algorithmString, expression [, iterationInt])
Calculate the hash value using an algorithm, and repeat this process for a
number of iterations.
This function supports MD5, SHA-1, SHA-224, SHA-256, SHA-384, SHA-
512, SHA3-224, SHA3-256, SHA3-384, and SHA3-512 algorithms. SHA-224,
SHA-384, and SHA-512 may be unavailable in some JREs.
MD5 and SHA-1 algorithms should not be considered as secure.
If this function is used to encrypt a password, a random salt should be
concatenated with a password and this salt and result of the function
should be stored to prevent a rainbow table attack and number of
iterations should be large enough to slow down a dictionary or a brute
force attack.
This method returns bytes.
Example:
CALL HASH('SHA-256', 'Text', 1000)
CALL HASH('SHA3-256', X'0102')
TRUNC
{ TRUNC | TRUNCATE } ( { {numeric [, digitsInt] }
| { timestamp | timestampWithTimeZone | date | timestampString } } )
COMPRESS
COMPRESS(dataBytes [, algorithmString])
EXPAND
EXPAND(bytes)
Expands data that was compressed using the COMPRESS function. This
method returns bytes.
Example:
UTF8TOSTRING(EXPAND(COMPRESS(STRINGTOUTF8('Test'))))
ZERO
ZERO()
Returns the value 0. This function can be used even if numeric literals are
disabled.
Example:
ZERO()
String Functions
ASCII
ASCII(string)
243 of 428
Returns the ASCII value of the first character in the string. This method
returns an int.
Example:
ASCII('Hi')
BIT_LENGTH
BIT_LENGTH(bytes)
Returns the number of bits in a binary string. This method returns a long.
Example:
BIT_LENGTH(NAME)
CHAR_LENGTH
{ CHAR_LENGTH | CHARACTER_LENGTH | { LENGTH } } ( string )
OCTET_LENGTH
OCTET_LENGTH(bytes)
CHAR
{ CHAR | CHR } ( int )
Returns the character that represents the ASCII value. This method
returns a string.
Example:
244 of 428
CHAR(65)
CONCAT
CONCAT(string, string [,...])
Combines strings. Unlike with the operator ||, NULL parameters are
ignored, and do not cause the result to become NULL. If all parameters are
NULL the result is an empty string. This method returns a string.
Example:
CONCAT(NAME, '!')
CONCAT_WS
CONCAT_WS(separatorString, string, string [,...])
DIFFERENCE
DIFFERENCE(string, string)
Returns the difference between the sounds of two strings. The difference
is calculated as a number of matched characters in the same positions in
SOUNDEX representations of arguments. This method returns an int
between 0 and 4 inclusive, or null if any of its parameters is null. Note that
value of 0 means that strings are not similar to each other. Value of 4
means that strings are fully similar to each other (have the same
SOUNDEX representation).
Example:
DIFFERENCE(T1.NAME, T2.NAME)
245 of 428
HEXTORAW
HEXTORAW(string)
RAWTOHEX
RAWTOHEX({string|bytes})
INSERT Function
INSERT(originalString, startInt, lengthInt, addString)
LOWER
{ LOWER | { LCASE } } ( string )
UPPER
{ UPPER | { UCASE } } ( string )
246 of 428
Converts a string to uppercase.
Example:
UPPER(NAME)
LEFT
LEFT(string, int)
RIGHT
RIGHT(string, int)
LOCATE
{ LOCATE(searchString, string [, startInt]) }
| { INSTR(string, searchString, [, startInt]) }
| { POSITION(searchString, string) }
LPAD
LPAD(string, int[, paddingString])
247 of 428
Left pad the string to the specified length. If the length is shorter than the
string, it will be truncated at the end. If the padding string is not set,
spaces will be used.
Example:
LPAD(AMOUNT, 10, '*')
RPAD
RPAD(string, int[, paddingString])
Right pad the string to the specified length. If the length is shorter than
the string, it will be truncated. If the padding string is not set, spaces will
be used.
Example:
RPAD(TEXT, 10, '-')
LTRIM
LTRIM(string [, characterToTrimString])
RTRIM
RTRIM(string [, characterToTrimString])
TRIM
TRIM ( [ [ LEADING | TRAILING | BOTH ] [ string ] FROM ] string )
248 of 428
Removes all leading spaces, trailing spaces, or spaces at both ends, from
a string. Other characters can be removed as well.
Example:
TRIM(BOTH '_' FROM NAME)
REGEXP_REPLACE
REGEXP_REPLACE(inputString, regexString, replacementString [,
flagsString])
REGEXP_LIKE
REGEXP_LIKE(inputString, regexString [, flagsString])
249 of 428
'i' enables case insensitive matching (Pattern.CASE_INSENSITIVE)
'c' disables case insensitive matching (Pattern.CASE_INSENSITIVE)
'n' allows the period to match the newline character (Pattern.DOTALL)
'm' enables multiline mode (Pattern.MULTILINE)
Example:
REGEXP_LIKE('Hello World', '[A-Z ]*', 'i')
REGEXP_SUBSTR
REGEXP_SUBSTR(inputString, regexString [, positionInt, occurrenceInt,
flagsString, groupInt])
REPEAT
REPEAT(string, int)
250 of 428
Returns a string repeated some number of times.
Example:
REPEAT(NAME || ' ', 10)
REPLACE
REPLACE(string, searchString [, replacementString])
SOUNDEX
SOUNDEX(string)
SPACE
SPACE(int)
STRINGDECODE
STRINGDECODE(string)
Converts a encoded string using the Java string literal encoding format.
Special characters are \b, \t, \n, \f, \r, \", \\, \<octal>, \u<unicode>. This
method returns a string.
251 of 428
Example:
CALL STRINGENCODE(STRINGDECODE('Lines 1\nLine 2'))
STRINGENCODE
STRINGENCODE(string)
STRINGTOUTF8
STRINGTOUTF8(string)
Encodes a string to a byte array using the UTF8 encoding format. This
method returns bytes.
Example:
CALL UTF8TOSTRING(STRINGTOUTF8('This is a test'))
SUBSTRING
SUBSTRING ( {string|bytes} FROM startInt [ FOR lengthInt ] )
| { { SUBSTRING | SUBSTR } ( {string|bytes}, startInt [, lengthInt ] ) }
UTF8TOSTRING
UTF8TOSTRING(bytes)
252 of 428
Example:
CALL UTF8TOSTRING(STRINGTOUTF8('This is a test'))
QUOTE_IDENT
QUOTE_IDENT(string)
XMLATTR
XMLATTR(nameString, valueString)
XMLNODE
XMLNODE(elementString [, attributesString [, contentString [,
indentBoolean]]])
XMLCOMMENT
XMLCOMMENT(commentString)
253 of 428
Example:
CALL XMLCOMMENT('Test')
XMLCDATA
XMLCDATA(valueString)
Creates an XML CDATA element. If the value contains ]]>, an XML text
element is created instead. This method returns a string.
Example:
CALL XMLCDATA('data')
XMLSTARTDOC
XMLSTARTDOC()
XMLTEXT
XMLTEXT(valueString [, escapeNewlineBoolean])
TO_CHAR
TO_CHAR(value [, formatString[, nlsParamString]])
254 of 428
TRANSLATE
TRANSLATE(value, searchString, replacementString)
CURRENT_TIME
CURRENT_TIME [ (int) ]
Returns the current time with time zone. If fractional seconds precision is
specified it should be from 0 to 9, 0 is default. The specified value can be
used only to limit precision of a result. The actual maximum available
precision depends on operating system and JVM and can be 3
(milliseconds) or higher. Higher precision is not available before Java 9.
This function returns the same value within a transaction (default) or
within a command depending on database mode.
SET TIME ZONE command reevaluates the value for this function using the
same original UTC timestamp of transaction.
Example:
255 of 428
CURRENT_TIME
CURRENT_TIME(9)
CURRENT_TIMESTAMP
CURRENT_TIMESTAMP [ (int) ]
Returns the current timestamp with time zone. Time zone offset is set to a
current time zone offset. If fractional seconds precision is specified it
should be from 0 to 9, 6 is default. The specified value can be used only to
limit precision of a result. The actual maximum available precision
depends on operating system and JVM and can be 3 (milliseconds) or
higher. Higher precision is not available before Java 9.
This function returns the same value within a transaction (default) or
within a command depending on database mode.
SET TIME ZONE command reevaluates the value for this function using the
same original UTC timestamp of transaction.
Example:
CURRENT_TIMESTAMP
CURRENT_TIMESTAMP(9)
LOCALTIME
LOCALTIME [ (int) ]
Returns the current time without time zone. If fractional seconds precision
is specified it should be from 0 to 9, 0 is default. The specified value can
be used only to limit precision of a result. The actual maximum available
precision depends on operating system and JVM and can be 3
(milliseconds) or higher. Higher precision is not available before Java 9.
These functions return the same value within a transaction (default) or
within a command depending on database mode.
SET TIME ZONE command reevaluates the value for these functions using
the same original UTC timestamp of transaction.
Example:
LOCALTIME
LOCALTIME(9)
256 of 428
LOCALTIMESTAMP
LOCALTIMESTAMP [ (int) ]
DATEADD
{ DATEADD| TIMESTAMPADD } (datetimeField, addIntLong, dateAndTime)
Adds units to a date-time value. The datetimeField indicates the unit. Use
negative values to subtract units. addIntLong may be a long value when
manipulating milliseconds, microseconds, or nanoseconds otherwise its
range is restricted to int. This method returns a value with the same type
as specified value if unit is compatible with this value. If specified field is a
HOUR, MINUTE, SECOND, MILLISECOND, etc and value is a DATE value
DATEADD returns combined TIMESTAMP. Fields DAY, MONTH, YEAR,
WEEK, etc are not allowed for TIME values. Fields TIMEZONE_HOUR,
TIMEZONE_MINUTE, and TIMEZONE_SECOND are only allowed for
TIMESTAMP WITH TIME ZONE values.
Example:
257 of 428
DATEADD(MONTH, 1, DATE '2001-01-31')
DATEDIFF
{ DATEDIFF | TIMESTAMPDIFF } (datetimeField, aDateAndTime,
bDateAndTime)
DATE_TRUNC
DATE_TRUNC (datetimeField, dateAndTime)
DAYNAME
DAYNAME(dateAndTime)
DAY_OF_MONTH
DAY_OF_MONTH({dateAndTime|interval})
ISO_DAY_OF_WEEK
ISO_DAY_OF_WEEK(dateAndTime)
DAY_OF_YEAR
DAY_OF_YEAR({dateAndTime|interval})
EXTRACT
EXTRACT ( datetimeField FROM { dateAndTime | interval })
Returns a value of the specific time unit from a date/time value. This
method returns a numeric value with EPOCH field and an int for all other
fields.
Example:
EXTRACT(SECOND FROM CURRENT_TIMESTAMP)
259 of 428
FORMATDATETIME
FORMATDATETIME ( dateAndTime, formatString
[ , localeString [ , timeZoneString ] ] )
HOUR
HOUR({dateAndTime|interval})
MINUTE
MINUTE({dateAndTime|interval})
MONTH
MONTH({dateAndTime|interval})
260 of 428
Returns the month (1-12) from a date/time value.
This function is deprecated, use EXTRACT instead of it.
Example:
MONTH(CREATED)
MONTHNAME
MONTHNAME(dateAndTime)
PARSEDATETIME
PARSEDATETIME(string, formatString
[, localeString [, timeZoneString]])
Parses a string and returns a TIMESTAMP WITH TIME ZONE value. The
most important format characters are: y year, M month, d day, H hour, m
minute, s second. For details of the format, see
java.time.format.DateTimeFormatter.
If timeZoneString is specified, it is used as default.
Example:
CALL PARSEDATETIME('Sat, 3 Feb 2001 03:05:06 GMT',
'EEE, d MMM yyyy HH:mm:ss z', 'en', 'GMT')
QUARTER
QUARTER(dateAndTime)
261 of 428
SECOND
SECOND(dateAndTime)
WEEK
WEEK(dateAndTime)
ISO_WEEK
ISO_WEEK(dateAndTime)
YEAR
YEAR({dateAndTime|interval})
ISO_YEAR
ISO_YEAR(dateAndTime)
System Functions
ABORT_SESSION
ABORT_SESSION(sessionInt)
ARRAY_GET
ARRAY_GET(arrayExpression, indexExpression)
263 of 428
CARDINALITY
{ CARDINALITY | { ARRAY_LENGTH } } (arrayExpression)
Returns the length of an array. Returns NULL if the specified array is NULL.
Example:
CALL CARDINALITY(ARRAY['Hello', 'World'])
ARRAY_CONTAINS
ARRAY_CONTAINS(arrayExpression, value)
Returns a boolean TRUE if the array contains the value or FALSE if it does
not contain it. Returns NULL if the specified array is NULL.
Example:
CALL ARRAY_CONTAINS(ARRAY['Hello', 'World'], 'Hello')
ARRAY_CAT
ARRAY_CAT(arrayExpression, arrayExpression)
ARRAY_APPEND
ARRAY_APPEND(arrayExpression, value)
264 of 428
ARRAY_MAX_CARDINALITY
ARRAY_MAX_CARDINALITY(arrayExpression)
TRIM_ARRAY
TRIM_ARRAY(arrayExpression, int)
Removes the specified number of elements from the end of the array.
Returns NULL if second parameter is NULL or if first parameter is NULL
and second parameter is not negative. Throws exception if second
parameter is negative or larger than number of elements in array.
Otherwise returns the truncated array.
Example:
CALL TRIM_ARRAY(ARRAY[1, 2, 3, 4], 1)
ARRAY_SLICE
ARRAY_SLICE(arrayExpression, lowerBoundInt, upperBoundInt)
Returns elements from the array as specified by the lower and upper
bound parameters. Both parameters are inclusive and the first element
has index 1, i.e. ARRAY_SLICE(a, 2, 2) has only the second element.
Returns NULL if any parameter is NULL or if an index is out of bounds.
Example:
CALL ARRAY_SLICE(ARRAY[1, 2, 3, 4], 1, 3)
AUTOCOMMIT
AUTOCOMMIT()
CANCEL_SESSION
CANCEL_SESSION(sessionInt)
CASEWHEN Function
CASEWHEN(boolean, aValue, bValue)
COALESCE
{ COALESCE | { NVL } } (aValue, bValue [,...])
| IFNULL(aValue, bValue)
CONVERT
CONVERT(value, dataTypeOrDomain)
266 of 428
CONVERT(NAME, INT)
CURRVAL
CURRVAL( [ schemaNameString, ] sequenceString )
Returns the latest generated value of the sequence for the current
session. Current value may only be requested after generation of the
sequence value in the current session. This method exists only for
compatibility, when it isn't required use CURRENT VALUE FOR
sequenceName instead. If the schema name is not set, the current
schema is used. When sequence is not found, the uppercase name is also
checked. This method returns a long.
Example:
CURRVAL('TEST_SEQ')
CSVWRITE
CSVWRITE ( fileNameString, queryString [, csvOptions [, lineSepString] ] )
267 of 428
CALL CSVWRITE('data/test.tsv', 'SELECT * FROM TEST', 'charset=UTF-8
fieldSeparator=' || CHAR(9));
CURRENT_SCHEMA
CURRENT_SCHEMA | SCHEMA()
CURRENT_CATALOG
CURRENT_CATALOG | DATABASE()
DATABASE_PATH
DATABASE_PATH()
Returns the directory of the database files and the database name, if it is
file based. Returns NULL otherwise.
Example:
CALL DATABASE_PATH();
DATA_TYPE_SQL
DATA_TYPE_SQL
(objectSchemaString, objectNameString, objectTypeString,
typeIdentifierString)
268 of 428
For domains object type is 'DOMAIN' and type identifier is the value of
INFORMATION_SCHEMA.DOMAINS.DTD_IDENTIFIER.
For columns object type is 'TABLE' and type identifier is the value of
INFORMATION_SCHEMA.COLUMNS.DTD_IDENTIFIER.
For routines object name is the value of
INFORMATION_SCHEMA.ROUTINES.SPECIFIC_NAME, object type is
'ROUTINE', and type identifier is the value of
INFORMATION_SCHEMA.ROUTINES.DTD_IDENTIFIER for data type of the
result and the value of
INFORMATION_SCHEMA.PARAMETERS.DTD_IDENTIFIER for data types of
arguments. Aggregate functions aren't supported by this function,
because their data type isn't statically known.
This function returns NULL if any argument is NULL, object type is not
valid, or object isn't found.
Example:
DATA_TYPE_SQL('PUBLIC', 'C', 'CONSTANT', 'TYPE')
DATA_TYPE_SQL('PUBLIC', 'D', 'DOMAIN', 'TYPE')
DATA_TYPE_SQL('PUBLIC', 'T', 'TABLE', '1')
DATA_TYPE_SQL('PUBLIC', 'R_1', 'ROUTINE', 'RESULT')
DATA_TYPE_SQL('PUBLIC', 'R_1', 'ROUTINE', '1')
COALESCE(
QUOTE_IDENT(DOMAIN_SCHEMA) || '.' ||
QUOTE_IDENT(DOMAIN_NAME),
DATA_TYPE_SQL(TABLE_SCHEMA, TABLE_NAME, 'TABLE',
DTD_IDENTIFIER))
DB_OBJECT_ID
DB_OBJECT_ID({{'ROLE'|'SETTING'|'SCHEMA'|'USER'}, objectNameString
| {'CONSTANT'|'CONSTRAINT'|'DOMAIN'|'INDEX'|'ROUTINE'|'SEQUENCE'
|'SYNONYM'|'TABLE'|'TRIGGER'}, schemaNameString,
objectNameString })
DB_OBJECT_SQL
DB_OBJECT_SQL({{'ROLE'|'SETTING'|'SCHEMA'|'USER'},
objectNameString
| {'CONSTANT'|'CONSTRAINT'|'DOMAIN'|'INDEX'|'ROUTINE'|'SEQUENCE'
|'SYNONYM'|'TABLE'|'TRIGGER'}, schemaNameString,
objectNameString })
DECODE
DECODE(value, whenValue, thenValue [,...])
DISK_SPACE_USED
DISK_SPACE_USED(tableNameString)
270 of 428
Returns the approximate amount of space used by the table specified.
Does not currently take into account indexes or LOB's. This function may
be expensive since it has to load every page in the table.
Example:
CALL DISK_SPACE_USED('my_table');
SIGNAL
SIGNAL(sqlStateString, messageString)
ESTIMATED_ENVELOPE
ESTIMATED_ENVELOPE(tableNameString, columnNameString)
Returns the estimated minimum bounding box that encloses all specified
GEOMETRY values. Only 2D coordinate plane is supported. NULL values
are ignored. Column must have a spatial index. This function is fast, but
estimation may include uncommitted data (including data from other
transactions), may return approximate bounds, or be different with actual
value due to other reasons. Use with caution. If estimation is not available
this function returns NULL. For accurate and reliable result use ESTIMATE
aggregate function instead.
Example:
CALL ESTIMATED_ENVELOPE('MY_TABLE', 'GEOMETRY_COLUMN');
FILE_READ
FILE_READ(fileNameString [,encodingString])
Returns the contents of a file. If only one parameter is supplied, the data
are returned as a BLOB. If two parameters are used, the data is returned
as a CLOB (text). The second parameter is the character set to use, NULL
meaning the default character set for this system.
271 of 428
File names and URLs are supported. To read a stream from the classpath,
use the prefix classpath:.
Admin rights are required to execute this command.
Example:
SELECT LENGTH(FILE_READ('~/.h2.server.properties')) LEN;
SELECT FILE_READ('http://localhost:8182/stylesheet.css', NULL) CSS;
FILE_WRITE
FILE_WRITE(blobValue, fileNameString)
Write the supplied parameter into a file. Return the number of bytes
written.
Write access to folder, and admin rights are required to execute this
command.
Example:
SELECT FILE_WRITE('Hello world', '/tmp/hello.txt')) LEN;
GREATEST
GREATEST(aValue, bValue [,...])
Returns the largest value that is not NULL, or NULL if all values are NULL.
Example:
CALL GREATEST(1, 2, 3);
LEAST
LEAST(aValue, bValue [,...])
Returns the smallest value that is not NULL, or NULL if all values are NULL.
Example:
CALL LEAST(1, 2, 3);
LOCK_MODE
LOCK_MODE()
272 of 428
Returns the current lock mode. See SET LOCK_MODE. This method returns
an int.
Example:
CALL LOCK_MODE();
LOCK_TIMEOUT
LOCK_TIMEOUT()
MEMORY_FREE
MEMORY_FREE()
Returns the free memory in KB (where 1024 bytes is a KB). This method
returns a long. The garbage is run before returning the value. Admin
rights are required to execute this command.
Example:
MEMORY_FREE()
MEMORY_USED
MEMORY_USED()
Returns the used memory in KB (where 1024 bytes is a KB). This method
returns a long. The garbage is run before returning the value. Admin
rights are required to execute this command.
Example:
MEMORY_USED()
NEXTVAL
NEXTVAL ( [ schemaNameString, ] sequenceString )
Increments the sequence and returns its value. The current value of the
sequence and the last identity in the current session are updated with the
273 of 428
generated value. Used values are never re-used, even when the
transaction is rolled back. This method exists only for compatibility, it's
recommended to use the standard NEXT VALUE FOR sequenceName
instead. If the schema name is not set, the current schema is used. When
sequence is not found, the uppercase name is also checked. This method
returns a long.
Example:
NEXTVAL('TEST_SEQ')
NULLIF
NULLIF(aValue, bValue)
NVL2
NVL2(testValue, aValue, bValue)
If the test value is null, then 'b' is returned. Otherwise, 'a' is returned. The
data type of the returned value is the data type of 'a' if this is a text type.
This function is provided for Oracle compatibility, use CASE or COALESCE
instead of it.
Example:
NVL2(X, 'not null', 'null')
READONLY
READONLY()
274 of 428
ROWNUM
ROWNUM()
Returns the number of the current row. This method returns a long value.
It is supported for SELECT statements, as well as for DELETE and UPDATE.
The first row has the row number 1, and is calculated before ordering and
grouping the result set, but after evaluating index conditions (even when
the index conditions are specified in an outer query). Use the
ROW_NUMBER() OVER () function to get row numbers after grouping or in
specified order.
Example:
SELECT ROWNUM(), * FROM TEST;
SELECT ROWNUM(), * FROM (SELECT * FROM TEST ORDER BY NAME);
SELECT ID FROM (SELECT T.*, ROWNUM AS R FROM TEST T) WHERE R
BETWEEN 2 AND 3;
SESSION_ID
SESSION_ID()
SET
SET(@variableName, value)
Updates a variable with the given value. The new value is returned. When
used in a query, the value is updated in the order the rows are read. When
used in a subquery, not all rows might be read depending on the query
plan. This can be used to implement running totals / cumulative sums.
Example:
SELECT X, SET(@I, COALESCE(@I, 0)+X) RUNNING_TOTAL FROM
SYSTEM_RANGE(1, 10)
275 of 428
TRANSACTION_ID
TRANSACTION_ID()
Returns the current transaction id for this session. This method returns
NULL if there is no uncommitted change, or if the database is not
persisted. Otherwise a value of the following form is returned: logFileId-
position-sessionId. This method returns a string. The value is unique
across database restarts (values are not re-used).
Example:
CALL TRANSACTION_ID()
TRUNCATE_VALUE
TRUNCATE_VALUE(value, precisionInt, forceBoolean)
CURRENT_PATH
CURRENT_PATH
CURRENT_ROLE
CURRENT_ROLE
H2VERSION
H2VERSION()
JSON Functions
JSON_OBJECT
JSON_OBJECT(
[{{[KEY] string VALUE expression} | {string : expression}} [,...] ]
[ { NULL | ABSENT } ON NULL ]
[ { WITH | WITHOUT } UNIQUE KEYS ]
)
JSON_ARRAY
JSON_ARRAY(
[expression [,...]]|{(query) [FORMAT JSON]}
[ { NULL | ABSENT } ON NULL ]
)
277 of 428
Returns a JSON array constructed from the specified values or from the
specified single-column subquery. If NULL ON NULL is specified NULL
values are included in the array.
Example:
JSON_ARRAY(10, 15, 20);
JSON_ARRAY(JSON_DATA_A FORMAT JSON, JSON_DATA_B FORMAT JSON);
JSON_ARRAY((SELECT J FROM PROPS) FORMAT JSON);
Table Functions
CSVREAD
CSVREAD(fileNameString [, columnsString [, csvOptions ] ] )
Returns the result set of reading the CSV (comma separated values) file.
For each parameter, NULL means the default value should be used.
If the column names are specified (a list of column names separated with
the fieldSeparator), those are used, otherwise (or if they are set to NULL)
the first line of the file is interpreted as the column names. In that case,
column names that contain no special characters (only letters, '_', and
digits; similar to the rule for Java identifiers) are processed is the same
way as unquoted identifiers and therefore case of characters may be
changed. Other column names are processed as quoted identifiers and
case of characters is preserved. To preserve the case of column names
unconditionally use caseSensitiveColumnNames option.
The default charset is the default value for this system, and the default
field separator is a comma. Missing unquoted values as well as data that
matches nullString is parsed as NULL. All columns are of type VARCHAR.
The BOM (the byte-order-mark) character 0xfeff at the beginning of the
file is ignored.
This function can be used like a table: SELECT * FROM CSVREAD(...).
Instead of a file, a URL may be used, for example
jar:file:///c:/temp/example.zip!/org/example/nested.csv. To read a stream
from the classpath, use the prefix classpath:. To read from HTTP, use the
prefix http: (as in a browser).
278 of 428
For performance reason, CSVREAD should not be used inside a join.
Instead, import the data first (possibly into a temporary table) and then
use the table.
Admin rights are required to execute this command.
Example:
SELECT * FROM CSVREAD('test.csv');
-- Read a file containing the columns ID, NAME with
SELECT * FROM CSVREAD('test2.csv', 'ID|NAME', 'charset=UTF-8
fieldSeparator=|');
SELECT * FROM CSVREAD('data/test.csv', null, 'rowSeparator=;');
-- Read a tab-separated file
SELECT * FROM CSVREAD('data/test.tsv', null, 'rowSeparator=' ||
CHAR(9));
SELECT "Last Name" FROM CSVREAD('address.csv');
SELECT "Last Name" FROM
CSVREAD('classpath:/org/acme/data/address.csv');
LINK_SCHEMA
LINK_SCHEMA (targetSchemaString, driverString, urlString,
userString, passwordString, sourceSchemaString)
Creates table links for all tables in a schema. If tables with the same name
already exist, they are dropped first. The target schema is created
automatically if it does not yet exist. The driver name may be empty if the
driver is already loaded. The list of tables linked is returned in the form of
a result set. Admin rights are required to execute this command.
Example:
SELECT * FROM LINK_SCHEMA('TEST2', '', 'jdbc:h2:./test2', 'sa', 'sa',
'PUBLIC');
TABLE
{ TABLE | TABLE_DISTINCT }
( { name dataTypeOrDomain = {array|rowValueExpression} } [,...] )
UNNEST
UNNEST(array, [,...]) [WITH ORDINALITY]
280 of 428
Aggregate Functions
Index
General Aggregate Functions
AVG
MAX
MIN
SUM
EVERY
ANY
COUNT
STDDEV_POP
STDDEV_SAMP
VAR_POP
VAR_SAMP
BIT_AND_AGG
BIT_OR_AGG
BIT_XOR_AGG
BIT_NAND_AGG
BIT_NOR_AGG
BIT_XNOR_AGG
ENVELOPE
Details
Non-standard syntax is marked in green. Compatibility-only non-standard
syntax is marked in red, don't use it unless you need it for compatibility
with other databases or old versions of H2.
The average (mean) value. If no rows are selected, the result is NULL.
Aggregates are only allowed in select statements.
The data type of result is DOUBLE PRECISION for TINYINT, SMALLINT,
INTEGER, and REAL arguments, NUMERIC with additional 10 decimal digits
of precision and scale for BIGINT and NUMERIC arguments; DECFLOAT
with additional 10 decimal digits of precision for DOUBLE PRECISION and
282 of 428
DECFLOAT arguments; INTERVAL with the same leading field precision, all
additional smaller datetime units in interval qualifier, and the maximum
scale for INTERVAL arguments.
Example:
AVG(X)
MAX
MAX(value)
[FILTER (WHERE expression)] [OVER windowNameOrSpecification]
The highest value. If no rows are selected, the result is NULL. Aggregates
are only allowed in select statements. The returned value is of the same
data type as the parameter.
Example:
MAX(NAME)
MIN
MIN(value)
[FILTER (WHERE expression)] [OVER windowNameOrSpecification]
The lowest value. If no rows are selected, the result is NULL. Aggregates
are only allowed in select statements. The returned value is of the same
data type as the parameter.
Example:
MIN(NAME)
SUM
SUM( [ DISTINCT|ALL ] { numeric | interval | { boolean } } )
[FILTER (WHERE expression)] [OVER windowNameOrSpecification]
The sum of all values. If no rows are selected, the result is NULL.
Aggregates are only allowed in select statements.
The data type of result is BIGINT for BOOLEAN, TINYINT, SMALLINT, and
INTEGER arguments; NUMERIC with additional 10 decimal digits of
precision for BIGINT and NUMERIC arguments; DOUBLE PRECISION for
REAL arguments, DECFLOAT with additional 10 decimal digits of precision
283 of 428
for DOUBLE PRECISION and DECFLOAT arguments; INTERVAL with
maximum precision and the same interval qualifier and scale for INTERVAL
arguments.
Example:
SUM(X)
EVERY
{EVERY| {BOOL_AND}}(boolean)
[FILTER (WHERE expression)] [OVER windowNameOrSpecification]
Returns true if all expressions are true. If no rows are selected, the result
is NULL. Aggregates are only allowed in select statements.
Example:
EVERY(ID>10)
ANY
{ANY|SOME| {BOOL_OR}}(boolean)
[FILTER (WHERE expression)] [OVER windowNameOrSpecification]
Returns true if any expression is true. If no rows are selected, the result is
NULL. Aggregates are only allowed in select statements.
Note that if ANY or SOME aggregate function is placed on the right side of
comparison operation or distinct predicate and argument of this function
is a subquery additional parentheses around aggregate function are
required, otherwise it will be parsed as quantified predicate.
Example:
ANY(NAME LIKE 'W%')
A = (ANY((SELECT B FROM T)))
COUNT
COUNT( { * | { [ DISTINCT|ALL ] expression } } )
[FILTER (WHERE expression)] [OVER windowNameOrSpecification]
The count of all row, or of the non-null values. This method returns a long.
If no rows are selected, the result is 0. Aggregates are only allowed in
select statements.
284 of 428
Example:
COUNT(*)
STDDEV_POP
STDDEV_POP( [ DISTINCT|ALL ] numeric )
[FILTER (WHERE expression)] [OVER windowNameOrSpecification]
STDDEV_SAMP
STDDEV_SAMP( [ DISTINCT|ALL ] numeric )
[FILTER (WHERE expression)] [OVER windowNameOrSpecification]
The sample standard deviation. This method returns a double. If less than
two rows are selected, the result is NULL. Aggregates are only allowed in
select statements.
Example:
STDDEV(X)
VAR_POP
VAR_POP( [ DISTINCT|ALL ] numeric )
[FILTER (WHERE expression)] [OVER windowNameOrSpecification]
VAR_SAMP
VAR_SAMP( [ DISTINCT|ALL ] numeric )
[FILTER (WHERE expression)] [OVER windowNameOrSpecification]
285 of 428
The sample variance (square of the sample standard deviation). This
method returns a double. If less than two rows are selected, the result is
NULL. Aggregates are only allowed in select statements.
Example:
VAR_SAMP(X)
BIT_AND_AGG
{{BIT_AND_AGG}|{BIT_AND}}(expression)
[FILTER (WHERE expression)] [OVER windowNameOrSpecification]
The bitwise AND of all non-null values. If no rows are selected, the result is
NULL. Aggregates are only allowed in select statements.
For non-aggregate function see BITAND.
Example:
BIT_AND_AGG(X)
BIT_OR_AGG
{{BIT_OR_AGG}|{BIT_OR}}(expression)
[FILTER (WHERE expression)] [OVER windowNameOrSpecification]
The bitwise OR of all non-null values. If no rows are selected, the result is
NULL. Aggregates are only allowed in select statements.
For non-aggregate function see BITOR.
Example:
BIT_OR_AGG(X)
BIT_XOR_AGG
BIT_XOR_AGG( [ DISTINCT|ALL ] expression)
[FILTER (WHERE expression)] [OVER windowNameOrSpecification]
The bitwise XOR of all non-null values. If no rows are selected, the result is
NULL. Aggregates are only allowed in select statements.
For non-aggregate function see BITXOR.
Example:
286 of 428
BIT_XOR_AGG(X)
BIT_NAND_AGG
BIT_NAND_AGG(expression)
[FILTER (WHERE expression)] [OVER windowNameOrSpecification]
The bitwise NAND of all non-null values. If no rows are selected, the result
is NULL. Aggregates are only allowed in select statements.
For non-aggregate function see BITNAND.
Example:
BIT_NAND_AGG(X)
BIT_NOR_AGG
BIT_NOR_AGG(expression)
[FILTER (WHERE expression)] [OVER windowNameOrSpecification]
The bitwise NOR of all non-null values. If no rows are selected, the result is
NULL. Aggregates are only allowed in select statements.
For non-aggregate function see BITNOR.
Example:
BIT_NOR_AGG(X)
BIT_XNOR_AGG
BIT_XNOR_AGG( [ DISTINCT|ALL ] expression)
[FILTER (WHERE expression)] [OVER windowNameOrSpecification]
The bitwise XNOR of all non-null values. If no rows are selected, the result
is NULL. Aggregates are only allowed in select statements.
For non-aggregate function see BITXNOR.
Example:
BIT_XNOR_AGG(X)
ENVELOPE
ENVELOPE( value )
[FILTER (WHERE expression)] [OVER windowNameOrSpecification]
287 of 428
Returns the minimum bounding box that encloses all specified GEOMETRY
values. Only 2D coordinate plane is supported. NULL values are ignored in
the calculation. If no rows are selected, the result is NULL. Aggregates are
only allowed in select statements.
Example:
ENVELOPE(X)
COVAR_SAMP
COVAR_SAMP(dependentExpression, independentExpression)
[FILTER (WHERE expression)] [OVER windowNameOrSpecification]
CORR
CORR(dependentExpression, independentExpression)
[FILTER (WHERE expression)] [OVER windowNameOrSpecification]
288 of 428
Pearson's correlation coefficient. This method returns a double. Rows in
which either argument is NULL are ignored in the calculation. If no rows
are selected, the result is NULL. Aggregates are only allowed in select
statements.
Example:
CORR(Y, X)
REGR_SLOPE
REGR_SLOPE(dependentExpression, independentExpression)
[FILTER (WHERE expression)] [OVER windowNameOrSpecification]
The slope of the line. This method returns a double. Rows in which either
argument is NULL are ignored in the calculation. If no rows are selected,
the result is NULL. Aggregates are only allowed in select statements.
Example:
REGR_SLOPE(Y, X)
REGR_INTERCEPT
REGR_INTERCEPT(dependentExpression, independentExpression)
[FILTER (WHERE expression)] [OVER windowNameOrSpecification]
The y-intercept of the regression line. This method returns a double. Rows
in which either argument is NULL are ignored in the calculation. If no rows
are selected, the result is NULL. Aggregates are only allowed in select
statements.
Example:
REGR_INTERCEPT(Y, X)
REGR_COUNT
REGR_COUNT(dependentExpression, independentExpression)
[FILTER (WHERE expression)] [OVER windowNameOrSpecification]
Returns the number of rows in the group. This method returns a long.
Rows in which either argument is NULL are ignored in the calculation. If no
rows are selected, the result is 0. Aggregates are only allowed in select
statements.
289 of 428
Example:
REGR_COUNT(Y, X)
REGR_R2
REGR_R2(dependentExpression, independentExpression)
[FILTER (WHERE expression)] [OVER windowNameOrSpecification]
REGR_AVGX
REGR_AVGX(dependentExpression, independentExpression)
[FILTER (WHERE expression)] [OVER windowNameOrSpecification]
REGR_AVGY
REGR_AVGY(dependentExpression, independentExpression)
[FILTER (WHERE expression)] [OVER windowNameOrSpecification]
290 of 428
REGR_SXX
REGR_SXX(dependentExpression, independentExpression)
[FILTER (WHERE expression)] [OVER windowNameOrSpecification]
REGR_SYY
REGR_SYY(dependentExpression, independentExpression)
[FILTER (WHERE expression)] [OVER windowNameOrSpecification]
REGR_SXY
REGR_SXY(dependentExpression, independentExpression)
[FILTER (WHERE expression)] [OVER windowNameOrSpecification]
ARRAY_AGG
ARRAY_AGG ( [ DISTINCT|ALL ] value
[ ORDER BY sortSpecificationList ] )
[FILTER (WHERE expression)] [OVER windowNameOrSpecification]
Aggregate the value into an array. This method returns an array. NULL
values are included in the array, FILTER clause can be used to exclude
them. If no rows are selected, the result is NULL. If ORDER BY is not
specified order of values is not determined. When this aggregate is used
with OVER clause that contains ORDER BY subclause it does not enforce
exact order of values. This aggregate needs additional own ORDER BY
clause to make it deterministic. Aggregates are only allowed in select
statements.
Example:
292 of 428
ARRAY_AGG(NAME ORDER BY ID)
ARRAY_AGG(NAME ORDER BY ID) FILTER (WHERE NAME IS NOT NULL)
ARRAY_AGG(ID ORDER BY ID) OVER (ORDER BY ID)
DENSE_RANK aggregate
DENSE_RANK(value [,...])
withinGroupSpecification
[FILTER (WHERE expression)] [OVER windowNameOrSpecification]
PERCENT_RANK aggregate
PERCENT_RANK(value [,...])
293 of 428
withinGroupSpecification
[FILTER (WHERE expression)] [OVER windowNameOrSpecification]
CUME_DIST aggregate
CUME_DIST(value [,...])
withinGroupSpecification
[FILTER (WHERE expression)] [OVER windowNameOrSpecification]
294 of 428
NULL. NULL values are ignored in the calculation. If no rows are selected,
the result is NULL. Aggregates are only allowed in select statements.
Example:
PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY V)
PERCENTILE_DISC
PERCENTILE_DISC(numeric) WITHIN GROUP (ORDER BY sortSpecification)
[FILTER (WHERE expression)] [OVER windowNameOrSpecification]
MEDIAN
MEDIAN( [ DISTINCT|ALL ] value )
[FILTER (WHERE expression)] [OVER windowNameOrSpecification]
The value separating the higher half of a values from the lower half.
Returns the middle value or an interpolated value between two middle
values if number of values is even. Interpolation is only supported for
numeric, date-time, and interval data types. NULL values are ignored in
the calculation. If no rows are selected, the result is NULL. Aggregates are
only allowed in select statements.
Example:
MEDIAN(X)
MODE
{ MODE() WITHIN GROUP (ORDER BY sortSpecification) }
| { MODE( value [ ORDER BY sortSpecification ] ) }
[FILTER (WHERE expression)] [OVER windowNameOrSpecification]
295 of 428
Returns the value that occurs with the greatest frequency. If there are
multiple values with the same frequency only one value will be returned.
In this situation value will be chosen based on optional ORDER BY clause
that should specify exactly the same expression as argument of this
function. Use ascending order to get smallest value or descending order to
get largest value from multiple values with the same frequency. If this
clause is not specified the exact chosen value is not determined in this
situation. NULL values are ignored in the calculation. If no rows are
selected, the result is NULL. Aggregates are only allowed in select
statements.
Example:
MODE() WITHIN GROUP (ORDER BY X)
Aggregates the keys with values into a JSON object. If ABSENT ON NULL is
specified properties with NULL value are not included in the object. If
WITH UNIQUE KEYS is specified the constructed object is checked for
uniqueness of keys, nested objects, if any, are checked too. If no values
are selected, the result is SQL NULL value.
Example:
JSON_OBJECTAGG(NAME: VAL);
JSON_OBJECTAGG(KEY NAME VALUE VAL);
JSON_ARRAYAGG
JSON_ARRAYAGG( [ DISTINCT|ALL ] expression
[ ORDER BY sortSpecificationList ]
[ { NULL | ABSENT } ON NULL ] )
[FILTER (WHERE expression)] [OVER windowNameOrSpecification]
296 of 428
Aggregates the values into a JSON array. If NULL ON NULL is specified
NULL values are included in the array. If no values are selected, the result
is SQL NULL value.
Example:
JSON_ARRAYAGG(NUMBER)
297 of 428
Window Functions
Index
Row Number Function
ROW_NUMBER
Rank Functions
RANK
DENSE_RANK
PERCENT_RANK
CUME_DIST
Details
Non-standard syntax is marked in green. Compatibility-only non-standard
syntax is marked in red, don't use it unless you need it for compatibility
with other databases or old versions of H2.
298 of 428
Returns the number of the current row starting with 1. Window frame
clause is not allowed for this function.
Window functions in H2 may require a lot of memory for large queries.
Example:
SELECT ROW_NUMBER() OVER (), * FROM TEST;
SELECT ROW_NUMBER() OVER (ORDER BY ID), * FROM TEST;
SELECT ROW_NUMBER() OVER (PARTITION BY CATEGORY ORDER BY ID), *
FROM TEST;
Rank Functions
RANK
RANK() OVER windowNameOrSpecification
Returns the rank of the current row. The rank of a row is the number of
rows that precede this row plus 1. If two or more rows have the same
values in ORDER BY columns, these rows get the same rank from the first
row with the same values. It means that gaps in ranks are possible. This
function requires window order clause. Window frame clause is not
allowed for this function.
Window functions in H2 may require a lot of memory for large queries.
See RANK aggregate for a hypothetical set function with the same name.
Example:
SELECT RANK() OVER (ORDER BY ID), * FROM TEST;
SELECT RANK() OVER (PARTITION BY CATEGORY ORDER BY ID), * FROM
TEST;
DENSE_RANK
DENSE_RANK() OVER windowNameOrSpecification
Returns the dense rank of the current row. The rank of a row is the
number of groups of rows with the same values in ORDER BY columns that
precede group with this row plus 1. If two or more rows have the same
values in ORDER BY columns, these rows get the same rank. Gaps in ranks
299 of 428
are not possible. This function requires window order clause. Window
frame clause is not allowed for this function.
Window functions in H2 may require a lot of memory for large queries.
See DENSE_RANK aggregate for a hypothetical set function with the same
name.
Example:
SELECT DENSE_RANK() OVER (ORDER BY ID), * FROM TEST;
SELECT DENSE_RANK() OVER (PARTITION BY CATEGORY ORDER BY ID), *
FROM TEST;
PERCENT_RANK
PERCENT_RANK() OVER windowNameOrSpecification
Returns the relative rank of the current row. The relative rank is
calculated as (RANK - 1) / (NR - 1), where RANK is a rank of the row and
NR is a number of rows in window partition with this row. Note that result
is always 0 if window order clause is not specified. Window frame clause is
not allowed for this function.
Window functions in H2 may require a lot of memory for large queries.
See PERCENT_RANK aggregate for a hypothetical set function with the
same name.
Example:
SELECT PERCENT_RANK() OVER (ORDER BY ID), * FROM TEST;
SELECT PERCENT_RANK() OVER (PARTITION BY CATEGORY ORDER BY ID),
* FROM TEST;
CUME_DIST
CUME_DIST() OVER windowNameOrSpecification
Returns the relative rank of the current row. The relative rank is
calculated as NP / NR where NP is a number of rows that precede the
current row or have the same values in ORDER BY columns and NR is a
number of rows in window partition with this row. Note that result is
always 1 if window order clause is not specified. Window frame clause is
not allowed for this function.
300 of 428
Window functions in H2 may require a lot of memory for large queries.
See CUME_DIST aggregate for a hypothetical set function with the same
name.
Example:
SELECT CUME_DIST() OVER (ORDER BY ID), * FROM TEST;
SELECT CUME_DIST() OVER (PARTITION BY CATEGORY ORDER BY ID), *
FROM TEST;
Returns the value in a next row with specified offset relative to the current
row. Offset must be non-negative. If IGNORE NULLS is specified rows with
null values in selected expression are skipped. If number of considered
rows is less than specified relative number this function returns NULL or
the specified default value, if any. If offset is 0 the value from the current
row is returned unconditionally. This function requires window order
clause. Window frame clause is not allowed for this function.
Window functions in H2 may require a lot of memory for large queries.
Example:
SELECT LEAD(X) OVER (ORDER BY ID), * FROM TEST;
SELECT LEAD(X, 2, 0) IGNORE NULLS OVER (
PARTITION BY CATEGORY ORDER BY ID
), * FROM TEST;
LAG
LAG(value [, offsetInt [, defaultValue]]) [{RESPECT|IGNORE} NULLS]
OVER windowNameOrSpecification
Returns the value in a previous row with specified offset relative to the
current row. Offset must be non-negative. If IGNORE NULLS is specified
rows with null values in selected expression are skipped. If number of
considered rows is less than specified relative number this function
301 of 428
returns NULL or the specified default value, if any. If offset is 0 the value
from the current row is returned unconditionally. This function requires
window order clause. Window frame clause is not allowed for this function.
Window functions in H2 may require a lot of memory for large queries.
Example:
SELECT LAG(X) OVER (ORDER BY ID), * FROM TEST;
SELECT LAG(X, 2, 0) IGNORE NULLS OVER (
PARTITION BY CATEGORY ORDER BY ID
), * FROM TEST;
LAST_VALUE
LAST_VALUE(value) [{RESPECT|IGNORE} NULLS]
OVER windowNameOrSpecification
302 of 428
SELECT LAST_VALUE(X) OVER (ORDER BY ID), * FROM TEST;
SELECT LAST_VALUE(X) IGNORE NULLS OVER (
PARTITION BY CATEGORY ORDER BY ID
RANGE BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
), * FROM TEST;
NTH_VALUE
NTH_VALUE(value, nInt) [FROM {FIRST|LAST}] [{RESPECT|IGNORE}
NULLS]
OVER windowNameOrSpecification
303 of 428
rows are distributed into 2 groups this function returns 1 for the first 3 row
and 2 for the last 2 rows. This function requires window order clause.
Window frame clause is not allowed for this function.
Window functions in H2 may require a lot of memory for large queries.
Example:
SELECT NTILE(10) OVER (ORDER BY ID), * FROM TEST;
SELECT NTILE(5) OVER (PARTITION BY CATEGORY ORDER BY ID), * FROM
TEST;
RATIO_TO_REPORT
RATIO_TO_REPORT(value)
OVER windowNameOrSpecification
Returns the ratio of a value to the sum of all values. If argument is NULL
or sum of all values is 0, then the value of function is NULL. Window
ordering and window frame clauses are not allowed for this function.
Window functions in H2 may require a lot of memory for large queries.
Example:
SELECT X, RATIO_TO_REPORT(X) OVER (PARTITION BY CATEGORY),
CATEGORY FROM TEST;
304 of 428
Data Types
Index
CHARACTER
CHARACTER VARYING
CHARACTER LARGE OBJECT
VARCHAR_IGNORECASE
BINARY
BINARY VARYING
BINARY LARGE OBJECT
BOOLEAN
TINYINT
SMALLINT
INTEGER
BIGINT
NUMERIC
REAL
DOUBLE PRECISION
DECFLOAT
DATE
TIME
TIME WITH TIME ZONE
TIMESTAMP
TIMESTAMP WITH TIME ZONE
INTERVAL
JAVA_OBJECT
ENUM
GEOMETRY
JSON
UUID
ARRAY
ROW
305 of 428
Details
Non-standard syntax is marked in green. Compatibility-only non-standard
syntax is marked in red, don't use it unless you need it for compatibility
with other databases or old versions of H2.
CHARACTER
{ CHARACTER | CHAR | NATIONAL { CHARACTER | CHAR } | NCHAR }
[ ( lengthInt [CHARACTERS|OCTETS] ) ]
CHARACTER VARYING
{ { CHARACTER | CHAR } VARYING
| VARCHAR
| { NATIONAL { CHARACTER | CHAR } | NCHAR } VARYING
| { VARCHAR_CASESENSITIVE } }
[ ( lengthInt [CHARACTERS|OCTETS] ) ]
306 of 428
The allowed length is from 1 to 1,000,000,000 characters. The length is a
size constraint; only the actual data is persisted. Length, if any, should be
specified in characters, CHARACTERS and OCTETS units have no effect in
H2.
The whole text is loaded into memory when using this data type. For large
text data CHARACTER LARGE OBJECT should be used; see there for
details.
See also string literal grammar. Mapped to java.lang.String.
Example:
CHARACTER VARYING(100)
VARCHAR(255)
BINARY
BINARY [ ( lengthInt ) ]
308 of 428
BINARY
BINARY(1000)
BINARY VARYING
{ BINARY VARYING | VARBINARY }
[ ( lengthInt ) ]
BINARY LARGE OBJECT is intended for very large binary values such as
files or images. Unlike when using BINARY VARYING, large objects are not
kept fully in-memory; instead, they are streamed. Use
PreparedStatement.setBinaryStream to store values. See also CHARACTER
LARGE OBJECT and Large Objects section.
Mapped to java.sql.Blob (java.io.InputStream is also supported).
Example:
BINARY LARGE OBJECT
BLOB(10K)
BOOLEAN
BOOLEAN
309 of 428
Possible values: TRUE, FALSE, and UNKNOWN (NULL).
See also boolean literal grammar. Mapped to java.lang.Boolean.
Example:
BOOLEAN
TINYINT
TINYINT
SMALLINT
SMALLINT
INTEGER
INTEGER | INT
310 of 428
Possible values: -2147483648 to 2147483647.
See also integer literal grammar. Mapped to java.lang.Integer.
Example:
INTEGER
INT
BIGINT
BIGINT
NUMERIC
{ NUMERIC | DECIMAL | DEC } [ ( precisionInt [ , scaleInt ] ) ]
Data type with fixed decimal precision and scale. This data type is
recommended for storing currency values.
If precision is specified, it must be from 1 to 100000. If scale is specified, it
must be from 0 to 100000, 0 is default.
See also numeric literal grammar. Mapped to java.math.BigDecimal.
Example:
NUMERIC(20, 2)
REAL
REAL | FLOAT ( precisionInt )
DOUBLE PRECISION
DOUBLE PRECISION | FLOAT [ ( precisionInt ) ]
DECFLOAT
DECFLOAT [ ( precisionInt ) ]
DATE
DATE
312 of 428
given date and time zone due to a daylight saving change).
java.time.LocalDate is also supported and recommended.
In org.h2.api.Aggregate, org.h2.api.AggregateFunction, and
org.h2.api.Trigger this data type is mapped to java.time.LocalDate.
If your time zone had LMT (local mean time) in the past and you use such
old dates (depends on the time zone, usually 100 or more years ago),
don't use java.sql.Date to read and write them.
If you deal with very old dates (before 1582-10-15) note that java.sql.Date
uses a mixed Julian/Gregorian calendar, java.util.GregorianCalendar can
be configured to proleptic Gregorian with setGregorianChange(new
java.util.Date(Long.MIN_VALUE)) and used to read or write fields of dates.
Example:
DATE
TIME
TIME [ ( precisionInt ) ] [ WITHOUT TIME ZONE ]
313 of 428
TIME WITH TIME ZONE
TIME [ ( precisionInt ) ] WITH TIME ZONE
The time with time zone data type. If fractional seconds precision is
specified it should be from 0 to 9, 0 is default.
See also time with time zone literal grammar. Mapped to
java.time.OffsetTime. Cast from higher fractional seconds precision to
lower fractional seconds precision performs round half up; if result of
rounding is higher than maximum supported value 23:59:59.999999999
the value is rounded down instead. The CAST operation to TIMESTAMP and
TIMESTAMP WITH TIME ZONE data types uses the CURRENT_DATE for date
fields.
Example:
TIME WITH TIME ZONE
TIME(9) WITH TIME ZONE
TIMESTAMP
TIMESTAMP [ ( precisionInt ) ] [ WITHOUT TIME ZONE ]
314 of 428
If your time zone had LMT (local mean time) in the past and you use such
old dates (depends on the time zone, usually 100 or more years ago),
don't use java.sql.Timestamp and java.util.Date to read and write them.
If you deal with very old dates (before 1582-10-15) note that
java.sql.Timestamp and java.util.Date use a mixed Julian/Gregorian
calendar, java.util.GregorianCalendar can be configured to proleptic
Gregorian with setGregorianChange(new java.util.Date(Long.MIN_VALUE))
and used to read or write fields of timestamps.
Cast from higher fractional seconds precision to lower fractional seconds
precision performs round half up.
Example:
TIMESTAMP
TIMESTAMP(9)
The timestamp with time zone data type. The proleptic Gregorian calendar
is used. If fractional seconds precision is specified it should be from 0 to 9,
6 is default.
See also timestamp with time zone literal grammar. Mapped to
java.time.OffsetDateTime. java.time.ZonedDateTime and java.time.Instant
are also supported.
Values of this data type are compared by UTC values. It means that 2010-
01-01 10:00:00+01 is greater than 2010-01-01 11:00:00+03.
Conversion to TIMESTAMP uses time zone offset to get UTC time and
converts it to local time using the system time zone. Conversion from
TIMESTAMP does the same operations in reverse and sets time zone offset
to offset of the system time zone. Cast from higher fractional seconds
precision to lower fractional seconds precision performs round half up.
Example:
TIMESTAMP WITH TIME ZONE
TIMESTAMP(9) WITH TIME ZONE
315 of 428
INTERVAL
intervalYearType | intervalMonthType | intervalDayType
| intervalHourType| intervalMinuteType | intervalSecondType
| intervalYearToMonthType | intervalDayToHourType
| intervalDayToMinuteType | intervalDayToSecondType
| intervalHourToMinuteType | intervalHourToSecondType
| intervalMinuteToSecondType
Interval data type. There are two classes of intervals. Year-month intervals
can store years and months. Day-time intervals can store days, hours,
minutes, and seconds. Year-month intervals are comparable only with
another year-month intervals. Day-time intervals are comparable only
with another day-time intervals.
Mapped to org.h2.api.Interval.
Example:
INTERVAL DAY TO SECOND
JAVA_OBJECT
{ JAVA_OBJECT | OBJECT | OTHER } [ ( lengthInt ) ]
This type allows storing serialized Java objects. Internally, a byte array
with serialized form is used. The allowed length is from 1 (useful only with
custom serializer) to 1,000,000,000 bytes. The length is a size constraint;
only the actual data is persisted.
Serialization and deserialization is done on the client side only with two
exclusions described below. Deserialization is only done when getObject is
called. Java operations cannot be executed inside the database engine for
security reasons. Use PreparedStatement.setObject with
Types.JAVA_OBJECT or H2Type.JAVA_OBJECT as a third argument to store
values.
If Java method alias has Object parameter(s), values are deserialized
during invocation of this method on the server side.
If a linked table has a column with Types.JAVA_OBJECT JDBC data type and
its database is not an another H2, Java objects need to be serialized and
deserialized during interaction between H2 and database that owns the
table on the server side of H2.
316 of 428
This data type needs special attention in secure environments.
Mapped to java.lang.Object (or any subclass).
Example:
JAVA_OBJECT
JAVA_OBJECT(10000)
ENUM
ENUM (string [, ... ])
GEOMETRY
GEOMETRY
[({ GEOMETRY |
{ POINT
| LINESTRING
| POLYGON
| MULTIPOINT
| MULTILINESTRING
| MULTIPOLYGON
| GEOMETRYCOLLECTION } [Z|M|ZM]}
[, sridInt] )]
317 of 428
type or dimension system of geometry. A constraint with required spatial
reference system identifier (SRID) can be set by specifying this identifier.
Mapped to org.locationtech.jts.geom.Geometry if JTS library is in classpath
and to java.lang.String otherwise. May be represented in textual format
using the WKT (well-known text) or EWKT (extended well-known text)
format. Values are stored internally in EWKB (extended well-known binary)
format, the maximum allowed length is 1,000,000,000 bytes. Only a
subset of EWKB and EWKT features is supported. Supported objects are
POINT, LINESTRING, POLYGON, MULTIPOINT, MULTILINESTRING,
MULTIPOLYGON, and GEOMETRYCOLLECTION. Supported dimension
systems are 2D (XY), Z (XYZ), M (XYM), and ZM (XYZM). SRID (spatial
reference system identifier) is supported.
Use a quoted string containing a WKT/EWKT formatted string or
PreparedStatement.setObject() to store values, and
ResultSet.getObject(..) or ResultSet.getString(..) to retrieve the values.
Example:
GEOMETRY
GEOMETRY(POINT)
GEOMETRY(POINT Z)
GEOMETRY(POINT Z, 4326)
GEOMETRY(GEOMETRY, 4326)
JSON
JSON [(lengthInt)]
318 of 428
Example:
JSON
UUID
UUID
Universally unique identifier. This is a 128 bit value. To store values, use
PreparedStatement.setBytes, setString, or setObject(uuid) (where uuid is
a java.util.UUID). ResultSet.getObject will return a java.util.UUID.
Please note that using an index on randomly generated data will result on
poor performance once there are millions of rows in a table. The reason is
that the cache behavior is very bad with randomly distributed data. This is
a problem for any database system.
For details, see the documentation of java.util.UUID.
Example:
UUID
ARRAY
baseDataType ARRAY [ '[' maximumCardinalityInt ']' ]
A data type for array of values. Base data type specifies the data type of
elements. Array may have NULL elements. Maximum cardinality, if any,
specifies maximum allowed number of elements in the array. The allowed
cardinality is from 0 to 65536 elements.
See also array literal grammar. Mapped to java.lang.Object[] (arrays of
any non-primitive type are also supported).
Use PreparedStatement.setArray(..) or PreparedStatement.setObject(..,
new Object[] {..}) to store values, and ResultSet.getObject(..) or
ResultSet.getArray(..) to retrieve the values.
Example:
BOOLEAN ARRAY
VARCHAR(100) ARRAY
INTEGER ARRAY[10]
319 of 428
ROW
ROW (fieldName dataType [,...])
A row value data type. This data type should not be normally used as data
type of a column.
See also row value expression grammar. Mapped to java.sql.ResultSet.
Example:
ROW(A INT, B VARCHAR(10))
INTERVAL MONTH
INTERVAL MONTH [ ( precisionInt ) ]
INTERVAL DAY
INTERVAL DAY [ ( precisionInt ) ]
320 of 428
Interval data type. If precision is specified it should be from 1 to 18, 2 is
default.
See also day interval literal grammar. Mapped to org.h2.api.Interval.
java.time.Duration is also supported.
Example:
INTERVAL DAY
INTERVAL HOUR
INTERVAL HOUR [ ( precisionInt ) ]
INTERVAL MINUTE
INTERVAL MINUTE [ ( precisionInt ) ]
INTERVAL SECOND
INTERVAL SECOND [ ( precisionInt [, fractionalPrecisionInt ] ) ]
321 of 428
See also second interval literal grammar. Mapped to org.h2.api.Interval.
java.time.Duration is also supported.
Example:
INTERVAL SECOND
323 of 428
fractionalPrecisionInt ) ]
324 of 428
SQL Grammar
Index
Literals
Value
Approximate numeric
Array
Boolean
Bytes
Date
Date and time
Dollar Quoted String
Exact numeric
Hex Number
Int
GEOMETRY
JSON
Long
Null
Number
Numeric
String
UUID
Time
Time with time zone
Timestamp
Timestamp with time zone
Interval
INTERVAL YEAR
INTERVAL MONTH
INTERVAL DAY
INTERVAL HOUR
INTERVAL MINUTE
INTERVAL SECOND
INTERVAL YEAR TO MONTH
INTERVAL DAY TO HOUR
325 of 428
INTERVAL DAY TO MINUTE
INTERVAL DAY TO SECOND
INTERVAL HOUR TO MINUTE
INTERVAL HOUR TO SECOND
INTERVAL MINUTE TO SECOND
Datetime fields
Datetime field
Year field
Month field
Day of month field
Hour field
Minute field
Second field
Timezone hour field
Timezone minute field
Timezone second field
Millennium field
Century field
Decade field
Quarter field
Millisecond field
Microsecond field
Nanosecond field
Day of year field
ISO day of week field
ISO week field
ISO week year field
Day of week field
Week field
Week year field
Epoch field
Other Grammar
Alias
And Condition
Array element reference
Field reference
326 of 428
Array value constructor by query
Case expression
Simple case
Searched case
Cast specification
Cipher
Column Definition
Column Constraint Definition
Comment
Bracketed comment
Compare
Condition
Condition Right Hand Side
Comparison Right Hand Side
Quantified Comparison Right Hand Side
Null Predicate Right Hand Side
Distinct Predicate Right Hand Side
Quantified Distinct Predicate Right Hand Side
Boolean Test Right Hand Side
Type Predicate Right Hand Side
JSON Predicate Right Hand Side
Between Predicate Right Hand Side
In Predicate Right Hand Side
Like Predicate Right Hand Side
Regexp Predicate Right Hand Side
Table Constraint Definition
Constraint Name Definition
Csv Options
Data Change Delta Table
Data Type or Domain
Data Type
Predefined Type
Digit
Expression
Factor
Grouping element
Hex
Index Column
327 of 428
Insert values
Interval qualifier
Join specification
Merge when clause
Merge when matched clause
Merge when not matched clause
Name
Operand
Override clause
Query
Quoted Name
Referential Constraint
References Specification
Referential Action
Script Compression Encryption
Select order
Row value expression
Select Expression
Sequence value expression
Sequence option
Alter sequence option
Alter identity column option
Basic sequence option
Set clause list
Sort specification
Sort specification list
Summand
Table Expression
Within group specification
Wildcard expression
Window name or specification
Window specification
Window frame
Window frame preceding
Window frame bound
Term
Time zone
Column
328 of 428
Details
Non-standard syntax is marked in green. Compatibility-only non-standard
syntax is marked in red, don't use it unless you need it for compatibility
with other databases or old versions of H2.
Literals
Value
string | { dollarQuotedString } | numeric | dateAndTime | boolean | bytes
| interval | array | { geometry | json | uuid } | null
Approximate numeric
[ + | - ] { { number [ . number ] } | { . number } }
E [ + | - ] expNumber
Array
ARRAY '[' [ expression [,...] ] ']'
An array of values.
Example:
329 of 428
ARRAY[1, 2]
ARRAY[1]
ARRAY[]
Boolean
TRUE | FALSE | UNKNOWN
A boolean value. UNKNOWN is a NULL value with the boolean data type.
Example:
TRUE
Bytes
X'hex' [ 'hex' [...] ]
A binary string value. The hex value is not case sensitive and may contain
space characters as separators. If there are more than one group of
quoted hex values, groups must be separated with whitespace.
Example:
X''
X'01FF'
X'01 bc 2a'
X'01' '02'
Date
DATE '[-]yyyy-MM-dd'
A date literal.
Example:
DATE '2004-12-31'
330 of 428
TIMESTAMP '1999-01-31 10:00:00'
A string starts and ends with two dollar signs. Two dollar signs are not
allowed within the text. A whitespace is required before the first set of
dollar signs. No escaping is required within the text.
Example:
$$John's car$$
Exact numeric
[ + | - ] { { number [ . number ] } | { . number } }
An exact numeric value. Exact numeric values with dot have NUMERIC
data type, values without dot small enough to fit into INTEGER data type
have this type, larger values small enough to fit into BIGINT data type
have this type, others also have NUMERIC data type.
Example:
-1600.05
Hex Number
[ + | - ] 0x { digit | a-f | A-F } [...]
Int
[ + | - ] number
JSON
JSON { bytes | string }
A binary or character string with a RFC 8259-compliant JSON text and data
format. JSON text is parsed into internal representation. Order of object
members is preserved as is. Duplicate object member names are allowed.
Example:
JSON '{"id":10,"name":"What''s this?"}'
JSON '[1, ' '2]';
JSON X'7472' '7565'
Long
[ + | - ] number
332 of 428
Null
NULL
Number
digit [...]
The maximum length of the number depends on the data type used.
Example:
100
Numeric
exactNumeric | approximateNumeric | int | long | { hexNumber }
The data type of a numeric literal is the one of numeric data types, such
as NUMERIC, DECFLOAT, BIGINT, or INTEGER depending on format and
value.
An explicit CAST can be used to change the data type.
Example:
-1600.05
CAST(0 AS DOUBLE PRECISION)
-1.4e-10
String
[N]'anything' [...]
| U&{'anything' [...]} [ UESCAPE 'anything' ]
A character string literal starts and ends with a single quote. Two single
quotes can be used to create a single quote inside a string. Prefix N
means a national character string literal; H2 does not distinguish regular
and national character string literals in any way, this prefix has no effect
in H2.
333 of 428
String literals staring with U& are Unicode character string literals. All
character string literals in H2 may have Unicode characters, but Unicode
character string literals may contain Unicode escape sequences \0000 or \
+000000, where \ is an escape character, 0000 and 000000 are Unicode
character codes in hexadecimal notation. Optional UESCAPE clause may
be used to specify another escape character, with exception for single
quote, double quote, plus sign, and hexadecimal digits (0-9, a-f, and A-F).
By default the backslash is used. Two escape characters can be used to
include a single character inside a string. Two single quotes can be used
to create a single quote inside a string.
Example:
'John''s car'
'A' 'B' 'C'
U&'W\00f6rter ' '\\ \+01f600 /'
U&'|00a1' UESCAPE '|'
UUID
UUID '{ digit | a-f | A-F | - } [...]'
Time
TIME [ WITHOUT TIME ZONE ] 'hh:mm:ss[.nnnnnnnnn]'
334 of 428
A time with time zone literal. A value is between 0:00:00 and
23:59:59.999999999 and has nanosecond resolution.
Example:
TIME WITH TIME ZONE '23:59:59+01'
TIME WITH TIME ZONE '10:15:30.334-03:30'
TIME WITH TIME ZONE '0:00:00Z'
Timestamp
TIMESTAMP [ WITHOUT TIME ZONE ] '[-]yyyy-MM-dd
hh:mm:ss[.nnnnnnnnn]'
A timestamp literal.
Example:
TIMESTAMP '2005-12-31 23:59:59'
A timestamp with time zone literal. If name of time zone is specified it will
be converted to time zone offset.
Example:
TIMESTAMP WITH TIME ZONE '2005-12-31 23:59:59Z'
TIMESTAMP WITH TIME ZONE '2005-12-31 23:59:59-10:00'
TIMESTAMP WITH TIME ZONE '2005-12-31 23:59:59.123+05'
TIMESTAMP WITH TIME ZONE '2005-12-31 23:59:59.123456789
Europe/London'
Interval
intervalYear | intervalMonth | intervalDay | intervalHour | intervalMinute
| intervalSecond | intervalYearToMonth | intervalDayToHour
| intervalDayToMinute | intervalDayToSecond | intervalHourToMinute
| intervalHourToSecond | intervalMinuteToSecond
An interval literal.
Example:
335 of 428
INTERVAL '1-2' YEAR TO MONTH
INTERVAL YEAR
INTERVAL [-|+] '[-|+]yearInt' YEAR [ ( precisionInt ) ]
INTERVAL MONTH
INTERVAL [-|+] '[-|+]monthInt' MONTH [ ( precisionInt ) ]
INTERVAL DAY
INTERVAL [-|+] '[-|+]dayInt' DAY [ ( precisionInt ) ]
INTERVAL HOUR
INTERVAL [-|+] '[-|+]hourInt' HOUR [ ( precisionInt ) ]
INTERVAL MINUTE
INTERVAL [-|+] '[-|+]minuteInt' MINUTE [ ( precisionInt ) ]
336 of 428
An INTERVAL MINUTE literal. If precision is specified it should be from 1 to
18.
Example:
INTERVAL '10' MINUTE
INTERVAL SECOND
INTERVAL [-|+] '[-|+]secondInt[.nnnnnnnnn]'
SECOND [ ( precisionInt [, fractionalPrecisionInt ] ) ]
337 of 428
Example:
INTERVAL '10 11:12' DAY TO MINUTE
338 of 428
An INTERVAL MINUTE TO SECOND literal. If leading field precision is
specified it should be from 1 to 18. If fractional seconds precision is
specified it should be from 0 to 9.
Example:
INTERVAL '11:12.123' MINUTE TO SECOND
Datetime fields
Datetime field
yearField | monthField | dayOfMonthField
| hourField | minuteField | secondField
| timezoneHourField | timezoneMinuteField
| { timezoneSecondField
| millenniumField | centuryField | decadeField
| quarterField
| millisecondField | microsecondField | nanosecondField
| dayOfYearField
| isoDayOfWeekField | isoWeekField | isoWeekYearField
| dayOfWeekField | weekField | weekYearField
| epochField }
Year field
YEAR | { YYYY | YY | SQL_TSI_YEAR }
Year.
Example:
YEAR
Month field
MONTH | { MM | M | SQL_TSI_MONTH }
Month (1-12).
Example:
339 of 428
MONTH
Hour field
HOUR | { HH | SQL_TSI_HOUR }
Hour (0-23).
Example:
HOUR
Minute field
MINUTE | { MI | N | SQL_TSI_MINUTE }
Minute (0-59).
Example:
MINUTE
Second field
SECOND | { SS | S | SQL_TSI_SECOND }
Second (0-59).
Example:
SECOND
Timezone second (from -59 to +59). Local mean time (LMT) used in the
past may have offsets with seconds. Standard time doesn't use such
offsets.
Example:
TIMEZONE_SECOND
Millennium field
MILLENNIUM
Century field
CENTURY
Decade field
DECADE
341 of 428
Decade, or ten years (2020-01-01 to 2029-12-31).
Example:
DECADE
Quarter field
QUARTER
Quarter (1-4).
Example:
QUARTER
Millisecond field
{ MILLISECOND } | { MS }
Millisecond (0-999).
Example:
MILLISECOND
Microsecond field
{ MICROSECOND } | { MCS }
Microsecond (0-999999).
Example:
MICROSECOND
Nanosecond field
{ NANOSECOND } | { NS }
Nanosecond (0-999999999).
Example:
NANOSECOND
ISO week of year (1-53). ISO definition is used when first week of year
should have at least four days and week is started with Monday.
Example:
ISO_WEEK
343 of 428
Week field
{ WEEK } | { WW | W | SQL_TSI_WEEK }
Epoch field
EPOCH
Other Grammar
Alias
name
344 of 428
And Condition
condition [ { AND condition } [...] ]
Value or condition.
Example:
ID=1 AND NAME='Hi'
Field reference
(expression).fieldName
Returns field value from the row value or NULL if row value is null. Row
value expression must be enclosed in parentheses.
Example:
(R).COL1
345 of 428
Case expression
simpleCase | searchedCase
Simple case
CASE expression
{ WHEN { expression | conditionRightHandSide } [,...] THEN expression }
[...]
[ ELSE expression ] END
Returns then expression from the first when clause where one of its
operands was was evaluated to TRUE for the case expression. If there are
no such clauses, returns else expression or NULL if it is absent.
Plain expressions are tested for equality with the case expression, NULL is
not equal to NULL. Right sides of conditions are evaluated with the case
expression on the left side.
Example:
CASE CNT WHEN IS NULL THEN 'Null' WHEN 0 THEN 'No' WHEN 1 THEN
'One' WHEN 2, 3 THEN 'Few' ELSE 'Some' END
Searched case
CASE { WHEN expression THEN expression } [...]
[ ELSE expression ] END
Returns the first expression where the condition is true. If no else part is
specified, return NULL.
Example:
CASE WHEN CNT<10 THEN 'Low' ELSE 'High' END
CASE WHEN A IS NULL THEN 'Null' ELSE 'Not null' END
346 of 428
Cast specification
CAST(value AS dataTypeOrDomain)
Converts a value to another data type. The following conversion rules are
used: When converting a number to a boolean, 0 is false and every other
value is true. When converting a boolean to a number, false is 0 and true
is 1. When converting a number to a number of another type, the value is
checked for overflow. When converting a string to binary, UTF-8 encoding
is used. Note that some data types may need explicitly specified precision
to avoid overflow or rounding.
Example:
CAST(NAME AS INT);
CAST(TIMESTAMP '2010-01-01 10:40:00.123456' AS TIME(6))
Cipher
AES
Column Definition
dataTypeOrDomain [ VISIBLE | INVISIBLE ]
[ { DEFAULT expression
| GENERATED ALWAYS AS (generatedColumnExpression)
| GENERATED {ALWAYS | BY DEFAULT} AS IDENTITY [(sequenceOption
[...])]} ]
[ ON UPDATE expression ]
[ DEFAULT ON NULL ]
[ SELECTIVITY selectivityInt ] [ COMMENT expression ]
[ columnConstraintDefinition ] [...]
The default expression is used if no explicit value was used when adding a
row and when DEFAULT value was specified in an update command.
A column is either a generated column or a base column. The generated
column has a generated column expression. The generated column
expression is evaluated and assigned whenever the row changes. This
347 of 428
expression may reference base columns of the table, but may not
reference other data. The value of the generated column cannot be set
explicitly. Generated columns may not have DEFAULT or ON UPDATE
expressions.
On update column expression is used if row is updated, at least one
column has a new value that is different from its previous value and value
for this column is not set explicitly in update statement.
Identity column is a column generated with a sequence. The column
declared as the identity column with IDENTITY data type or with IDENTITY
() clause is implicitly the primary key column of this table. GENERATED
ALWAYS AS IDENTITY, GENERATED BY DEFAULT AS IDENTITY, and
AUTO_INCREMENT clauses do not create the primary key constraint
automatically. GENERATED ALWAYS AS IDENTITY clause indicates that
column can only be generated by the sequence, its value cannot be set
explicitly. Identity column has implicit NOT NULL constraint. Identity
column may not have DEFAULT or ON UPDATE expressions.
DEFAULT ON NULL makes NULL value work as DEFAULT value is
assignments to this column.
The invisible column will not be displayed as a result of SELECT * query.
Otherwise, it works as normal column.
Column constraint definitions are not supported for ALTER statements.
Example:
CREATE TABLE TEST(ID INT PRIMARY KEY,
NAME VARCHAR(255) DEFAULT '' NOT NULL);
CREATE TABLE TEST(ID BIGINT GENERATED ALWAYS AS IDENTITY
PRIMARY KEY,
QUANTITY INT, PRICE NUMERIC(10, 2),
AMOUNT NUMERIC(20, 2) GENERATED ALWAYS AS (QUANTITY *
PRICE));
Comment
bracketedComment | -- anything | // anything
Bracketed comment
/* [ [ bracketedComment ] [ anything ] [...] ] */
349 of 428
Compare
<> | <= | >= | = | < | > | { != } | &&
Condition
operand [ conditionRightHandSide ]
| NOT condition
| EXISTS ( query )
| UNIQUE ( query )
| INTERSECTS (operand, operand)
350 of 428
| nullPredicateRightHandSide
| distinctPredicateRightHandSide
| quantifiedDistinctPredicateRightHandSide
| booleanTestRightHandSide
| typePredicateRightHandSide
| jsonPredicateRightHandSide
| betweenPredicateRightHandSide
| inPredicateRightHandSide
| likePredicateRightHandSide
| regexpPredicateRightHandSide
351 of 428
Quantified comparison predicates ANY and SOME return TRUE if specified
comparison operation between left size of condition and at least one row
from a subquery returns TRUE. ANY and SOME predicates return FALSE if
all such comparisons return FALSE. Otherwise they return UNKNOWN.
Note that these predicates have priority over ANY and SOME aggregate
functions with subquery on the right side. Use parentheses around
aggregate function.
Example:
< ALL(SELECT V FROM TEST)
353 of 428
IS OF (INTEGER, BIGINT)
354 of 428
This operation is logically equivalent to OR between comparison
operations comparing left side and each value from the right side.
Example:
IN (A, B, C)
IN (SELECT V FROM TEST)
Defines a constraint.
PRIMARY KEY and UNIQUE require unique values. PRIMARY KEY also
disallows NULL values and marks the column as a primary key, a table can
have only one primary key. UNIQUE constraint supports NULL values and
rows with NULL value in any column are considered as unique. UNIQUE
(VALUE) creates a unique constraint on entire row, excluding invisible
columns; but if new columns will be added to the table, they will not be
included into this constraint.
Referential constraint requires values that exist in other column(s)
(usually in another table).
Check constraint requires a specified condition to return TRUE or
UNKNOWN (NULL). It can reference columns of the table, and can
reference objects that exist while the statement is executed. Conditions
are only checked when a row is added or modified in the table where the
constraint exists.
Example:
PRIMARY KEY(ID, NAME)
Csv Options
charsetString [, fieldSepString [, fieldDelimString [, escString [,
nullString]]]]
| optionString
Executes the inner data change command and returns old, new, or final
rows.
OLD is not allowed for INSERT command. It returns old rows.
NEW and FINAL are not allowed for DELETE command.
NEW returns new rows after evaluation of default expressions, but before
execution of triggers.
357 of 428
FINAL returns new rows after execution of triggers.
Example:
SELECT ID FROM FINAL TABLE (INSERT INTO TEST (A, B) VALUES (1, 2))
Data Type
predefinedType | arrayType | rowType
A data type.
Example:
INTEGER
Predefined Type
characterType | characterVaryingType | characterLargeObjectType
| binaryType | binaryVaryingType | binaryLargeObjectType
| booleanType
| smallintType | integerType | bigintType
| numericType | realType | doublePrecisionType | decfloatType
| dateType | timeType | timeWithTimeZoneType
| timestampType | timestampWithTimeZoneType
| intervalType
| { tinyintType | javaObjectType | enumType
| geometryType | jsonType | uuidType }
358 of 428
Digit
0-9
A digit.
Example:
0
Expression
andCondition [ { OR andCondition } [...] ]
Value or condition.
Example:
ID=1 OR NAME='Hi'
Factor
term [ { { * | / | { % } } term } [...] ]
Grouping element
expression | (expression [, ...]) | ()
Hex
[' ' [...]] { { digit | a-f | A-F } [' ' [...]] { digit | a-f | A-F } [' ' [...]] } [...]
Index Column
columnName [ ASC | DESC ] [ NULLS { FIRST | LAST } ]
Insert values
VALUES { DEFAULT|expression | [ROW] ({DEFAULT|expression} [,...]) },
[,...]
Interval qualifier
YEAR [(precisionInt)] [ TO MONTH ]
| MONTH [(precisionInt)]
| DAY [(precisionInt)] [ TO { HOUR | MINUTE | SECOND [(scaleInt)] } ]
| HOUR [(precisionInt)] [ TO { MINUTE | SECOND [(scaleInt)] } ]
| MINUTE [(precisionInt)] [ TO SECOND [(scaleInt)] ]
| SECOND [(precisionInt [, scaleInt])]
An interval qualifier.
Example:
DAY TO SECOND
Join specification
ON expression | USING (columnName [,...])
360 of 428
Specifies a join condition or column names.
Example:
ON B.ID = A.PARENT_ID
USING (ID)
Name
{ { A-Z|_ } [ { A-Z|_|0-9 } [...] ] } | quotedName
361 of 428
With default settings unquoted names are converted to upper case. The
maximum name length is 256 characters.
Identifiers in H2 are case sensitive by default. Because unquoted names
are converted to upper case, they can be written in any case anyway.
When both quoted and unquoted names are used for the same identifier
the quoted names must be written in upper case. Identifiers with
lowercase characters can be written only as a quoted name, they aren't
accessible with unquoted names.
If DATABASE_TO_UPPER setting is set to FALSE the unquoted names aren't
converted to upper case.
If DATABASE_TO_LOWER setting is set to TRUE the unquoted names are
converted to lower case instead.
If CASE_INSENSITIVE_IDENTIFIERS setting is set to TRUE all identifiers are
case insensitive.
Example:
TEST
Operand
summand [ { || summand } [...] ]
Override clause
OVERRIDING { USER | SYSTEM } VALUE
362 of 428
If OVERRIDING USER VALUE is specified, INSERT statement ignores the
provided value for identity column and generates a new one instead.
If OVERRIDING SYSTEM VALUE is specified, INSERT statement assigns the
provided value to identity column.
If neither clauses are specified, INSERT statement assigns the provided
value to GENERATED BY DEFAULT AS IDENTITY column, but throws an
exception if value is specified for GENERATED ALWAYS AS IDENTITY
column.
Example:
OVERRIDING SYSTEM VALUE
OVERRIDING USER VALUE
Query
select | explicitTable | tableValue
Quoted Name
"anything"
| U&"anything" [ UESCAPE 'anything' ]
Referential Constraint
FOREIGN KEY ( columnName [,...] ) referencesSpecification
References Specification
REFERENCES [ refTableName ] [ ( refColumnName [,...] ) ]
[ ON DELETE referentialAction ] [ ON UPDATE referentialAction ]
Referential Action
CASCADE | RESTRICT | NO ACTION | SET { DEFAULT | NULL }
The action CASCADE will cause conflicting rows in the referencing (child)
table to be deleted or updated. RESTRICT is the default action. As this
database does not support deferred checking, RESTRICT and NO ACTION
364 of 428
will both throw an exception if the constraint is violated. The action SET
DEFAULT will set the column in the referencing (child) table to the default
value, while SET NULL will set it to NULL.
Example:
CASCADE
SET NULL
The compression and encryption algorithm to use for script files. When
using encryption, only DEFLATE and LZF are supported. LZF is faster but
uses more space.
Example:
COMPRESSION LZF
Select order
{ expression | { int } } [ ASC | DESC ] [ NULLS { FIRST | LAST } ]
365 of 428
ROW (1)
(1, 2)
1
Select Expression
wildcardExpression | expression [ [ AS ] columnAlias ]
Sequence option
START WITH long
| { RESTART WITH long }
366 of 428
| basicSequenceOption
Option of a sequence.
START WITH is used to set the initial value of the sequence. If initial value
is not defined, MINVALUE for incrementing sequences and MAXVALUE for
decrementing sequences is used.
RESTART is used to immediately restart the sequence with the specified
value.
Example:
START WITH 10000
NO CACHE
Option of a sequence.
START WITH is used to change the initial value of the sequence. It does
not affect the current value of the sequence, it only changes the
preserved initial value that is used for simple RESTART without a value.
RESTART is used to restart the sequence from its initial value or with the
specified value.
Example:
START WITH 10000
NO CACHE
367 of 428
changes the preserved initial value that is used for simple RESTART
without a value.
RESTART is used to restart the sequence from its initial value or with the
specified value.
Example:
START WITH 10000
SET NO CACHE
368 of 428
Set clause list
{ { columnName = { DEFAULT | expression } }
| { ( columnName [,...] ) = { rowValueExpression | (query) } } } [,...]
Sort specification
expression [ ASC | DESC ] [ NULLS { FIRST | LAST } ]
Summand
factor [ { { + | - } factor } [...] ]
369 of 428
Table Expression
{ [ schemaName. ] tableName
| ( query )
| unnest
| table
| dataChangeDeltaTable }
[ [ AS ] newTableAlias [ ( columnName [,...] ) ] ]
[ USE INDEX ([ indexName [,...] ]) ]
[ { { LEFT | RIGHT } [ OUTER ] | [ INNER ] | CROSS | NATURAL }
JOIN tableExpression [ joinSpecification ] ]
Joins a table. The join specification is not supported for cross and natural
joins. A natural join is an inner join, where the condition is automatically
on the columns with the same name.
Example:
TEST1 AS T1 LEFT JOIN TEST2 AS T2 ON T1.ID = T2.PARENT_ID
Wildcard expression
[[schemaName.]tableAlias.]*
[EXCEPT ([[schemaName.]tableAlias.]columnName, [,...])]
370 of 428
Window name or specification
windowName | windowSpecification
Window specification
([existingWindowName]
[PARTITION BY expression [,...]] [ORDER BY sortSpecificationList]
[windowFrame])
Window frame
ROWS|RANGE|GROUP
371 of 428
{windowFramePreceding|BETWEEN windowFrameBound AND
windowFrameBound}
[EXCLUDE {CURRENT ROW|GROUP|TIES|NO OTHERS}]
Term
{ value
| column
| ?[ int ]
| sequenceValueExpression
| function
| { - | + } term
| ( expression )
| arrayElementReference
| fieldReference
| ( query )
| caseExpression
| castSpecification
| userDefinedFunctionName }
[ timeZone | intervalQualifier ]
373 of 428
Interval qualifier may only be specified for a compatible value or for a
subtraction operation between two datetime values. The subtraction
operation ignores the leading field precision of the qualifier.
Example:
'Hello'
Time zone
AT { TIME ZONE { intervalHourToMinute | intervalHourToSecond | { string
} } | LOCAL }
A time zone. Converts the timestamp with or without time zone into
timestamp with time zone at specified time zone. If a day-time interval is
specified as a time zone, it may not have fractional seconds and must be
between -18 to 18 hours inclusive.
Example:
AT LOCAL
AT TIME ZONE '2'
AT TIME ZONE '-6:00'
AT TIME ZONE INTERVAL '10:00' HOUR TO MINUTE
AT TIME ZONE INTERVAL '10:00:00' HOUR TO SECOND
AT TIME ZONE 'UTC'
AT TIME ZONE 'Europe/London'
Column
[[schemaName.]tableAlias.] { columnName | { _ROWID_ } }
A column name with optional table alias and schema. _ROWID_ can be
used to access unique row identifier.
Example:
ID
374 of 428
System Tables
Index
Information Schema
CHECK_CONSTRAINTS
COLLATIONS
COLUMNS
COLUMN_PRIVILEGES
CONSTANTS
CONSTRAINT_COLUMN_USAGE
DOMAINS
DOMAIN_CONSTRAINTS
ELEMENT_TYPES
ENUM_VALUES
FIELDS
INDEXES
INDEX_COLUMNS
INFORMATION_SCHEMA_CATALOG_NAME
IN_DOUBT
KEY_COLUMN_USAGE
LOCKS
PARAMETERS
QUERY_STATISTICS
REFERENTIAL_CONSTRAINTS
RIGHTS
ROLES
ROUTINES
SCHEMATA
SEQUENCES
SESSIONS
SESSION_STATE
SETTINGS
SYNONYMS
TABLES
TABLE_CONSTRAINTS
TABLE_PRIVILEGES
375 of 428
TRIGGERS
USERS
VIEWS
Range Table
Information Schema
The system tables and views in the schema INFORMATION_SCHEMA
contain the meta data of all tables, views, domains, and other objects in
the database as well as the current settings. This documentation
describes the default new version of INFORMATION_SCHEMA for H2 2.0.
Old TCP clients (1.4.200 and below) see the legacy version of
INFORMATION_SCHEMA, because they can't work with the new one. The
legacy version is not documented.
CHECK_CONSTRAINTS
Contains CHECK clauses of check and domain constraints.
COLLATIONS
Contains available collations.
COLUMNS
Contains information about columns of tables.
377 of 428
NUMERIC_PRECISION INTEGER
The precision for numeric data types.
NUMERIC_PRECISION_RADIX INTEGER
The radix of precision (2 or 10) for numeric data types.
NUMERIC_SCALE INTEGER
The scale for numeric data types.
DATETIME_PRECISION INTEGER
The fractional seconds precision for datetime data types.
INTERVAL_TYPE CHARACTER VARYING
The data type of interval qualifier for interval data types.
INTERVAL_PRECISION INTEGER
The leading field precision for interval data types.
CHARACTER_SET_CATALOG CHARACTER VARYING
The catalog (database name) for character string data types.
CHARACTER_SET_SCHEMA CHARACTER VARYING
The name of public schema for character string data types.
CHARACTER_SET_NAME CHARACTER VARYING
The 'Unicode' for character string data types.
COLLATION_CATALOG CHARACTER VARYING
The catalog (database name) for character string data types.
COLLATION_SCHEMA CHARACTER VARYING
The name of public schema for character string data types.
COLLATION_NAME CHARACTER VARYING
The name of collation for character string data types.
DOMAIN_CATALOG CHARACTER VARYING
The catalog for columns with domain.
DOMAIN_SCHEMA CHARACTER VARYING
The schema of domain for columns with domain.
DOMAIN_NAME CHARACTER VARYING
The name of domain for columns with domain.
378 of 428
MAXIMUM_CARDINALITY INTEGER
The maximum cardinality for array data types.
DTD_IDENTIFIER CHARACTER VARYING
The data type identifier to read additional information from
INFORMATION_SCHEMA.ELEMENT_TYPES for array data types,
INFORMATION_SCHEMA.ENUM_VALUES for ENUM data type, and
INFORMATION_SCHEMA.FIELDS for row value data types.
IS_IDENTITY CHARACTER VARYING
Whether column is an identity column ('YES' or 'NO').
IDENTITY_GENERATION CHARACTER VARYING
Identity generation ('ALWAYS' or 'BY DEFAULT') for identity columns.
IDENTITY_START BIGINT
The initial start value for identity columns.
IDENTITY_INCREMENT BIGINT
The increment value for identity columns.
IDENTITY_MAXIMUM BIGINT
The maximum value for identity columns.
IDENTITY_MINIMUM BIGINT
The minimum value for identity columns.
IDENTITY_CYCLE CHARACTER VARYING
Whether identity values are cycled ('YES' or 'NO') for identity columns.
IS_GENERATED CHARACTER VARYING
Whether column is an generated column ('ALWAYS' or 'NEVER')
GENERATION_EXPRESSION CHARACTER VARYING
The SQL of GENERATED ALWAYS AS expression for generated columns.
DECLARED_DATA_TYPE CHARACTER VARYING
The declared SQL data type name for numeric data types.
DECLARED_NUMERIC_PRECISION INTEGER
The declared precision, if any, for numeric data types.
DECLARED_NUMERIC_SCALE INTEGER
The declared scale, if any, for numeric data types.
379 of 428
GEOMETRY_TYPE CHARACTER VARYING
The geometry type constraint, if any, for geometry data types.
GEOMETRY_SRID INTEGER
The geometry SRID (Spatial Reference Identifier) constraint, if any, for
geometry data types.
IDENTITY_BASE BIGINT
The current base value for identity columns.
IDENTITY_CACHE BIGINT
The cache size for identity columns.
COLUMN_ON_UPDATE CHARACTER VARYING
The SQL of ON UPDATE expression, if any.
IS_VISIBLE BOOLEAN
Whether column is visible (included into SELECT *).
DEFAULT_ON_NULL BOOLEAN
Whether value of DEFAULT expression is used when NULL value is
inserted.
SELECTIVITY INTEGER
The selectivity of a column (0-100), used to choose the best index.
REMARKS CHARACTER VARYING
Optional remarks.
COLUMN_PRIVILEGES
Contains information about privileges of columns. H2 doesn't have per-
column privileges, so this view actually contains privileges of their tables.
380 of 428
The schema of the table.
TABLE_NAME CHARACTER VARYING
The name of the table.
COLUMN_NAME CHARACTER VARYING
The name of the column.
PRIVILEGE_TYPE CHARACTER VARYING
'SELECT', 'INSERT', 'UPDATE', or 'DELETE'.
IS_GRANTABLE CHARACTER VARYING
Whether grantee may grant rights to this object to others ('YES' or 'NO').
CONSTANTS
Contains information about constants.
381 of 428
The catalog (database name) for character string data types.
CHARACTER_SET_SCHEMA CHARACTER VARYING
The name of public schema for character string data types.
CHARACTER_SET_NAME CHARACTER VARYING
The 'Unicode' for character string data types.
COLLATION_CATALOG CHARACTER VARYING
The catalog (database name) for character string data types.
COLLATION_SCHEMA CHARACTER VARYING
The name of public schema for character string data types.
COLLATION_NAME CHARACTER VARYING
The name of collation for character string data types.
NUMERIC_PRECISION INTEGER
The precision for numeric data types.
NUMERIC_PRECISION_RADIX INTEGER
The radix of precision (2 or 10) for numeric data types.
NUMERIC_SCALE INTEGER
The scale for numeric data types.
DATETIME_PRECISION INTEGER
The fractional seconds precision for datetime data types.
INTERVAL_TYPE CHARACTER VARYING
The data type of interval qualifier for interval data types.
INTERVAL_PRECISION INTEGER
The leading field precision for interval data types.
MAXIMUM_CARDINALITY INTEGER
The maximum cardinality for array data types.
DTD_IDENTIFIER CHARACTER VARYING
The data type identifier to read additional information from
INFORMATION_SCHEMA.ELEMENT_TYPES for array data types,
INFORMATION_SCHEMA.ENUM_VALUES for ENUM data type, and
INFORMATION_SCHEMA.FIELDS for row value data types.
DECLARED_DATA_TYPE CHARACTER VARYING
382 of 428
The declared SQL data type name for numeric data types.
DECLARED_NUMERIC_PRECISION INTEGER
The declared precision, if any, for numeric data types.
DECLARED_NUMERIC_SCALE INTEGER
The declared scale, if any, for numeric data types.
GEOMETRY_TYPE CHARACTER VARYING
The geometry type constraint, if any, for geometry data types.
GEOMETRY_SRID INTEGER
The geometry SRID (Spatial Reference Identifier) constraint, if any, for
geometry data types.
REMARKS CHARACTER VARYING
Optional remarks.
CONSTRAINT_COLUMN_USAGE
Contains information about columns used in constraints.
383 of 428
DOMAINS
Contains information about domains.
385 of 428
DOMAIN_ON_UPDATE CHARACTER VARYING
The SQL of ON UPDATE expression, if any.
PARENT_DOMAIN_CATALOG CHARACTER VARYING
The catalog (database name) for domains with parent domain.
PARENT_DOMAIN_SCHEMA CHARACTER VARYING
The schema of parent domain for domains with parent domain.
PARENT_DOMAIN_NAME CHARACTER VARYING
The name of parent domain for domains with parent domain.
REMARKS CHARACTER VARYING
Optional remarks.
DOMAIN_CONSTRAINTS
Contains basic information about domain constraints. See also
INFORMATION_SCHEMA.CHECK_CONSTRAINTS.
386 of 428
REMARKS CHARACTER VARYING
Optional remarks.
ELEMENT_TYPES
Contains information about types of array elements.
387 of 428
COLLATION_CATALOG CHARACTER VARYING
The catalog (database name) for character string data types.
COLLATION_SCHEMA CHARACTER VARYING
The name of public schema for character string data types.
COLLATION_NAME CHARACTER VARYING
The name of collation for character string data types.
NUMERIC_PRECISION INTEGER
The precision for numeric data types.
NUMERIC_PRECISION_RADIX INTEGER
The radix of precision (2 or 10) for numeric data types.
NUMERIC_SCALE INTEGER
The scale for numeric data types.
DATETIME_PRECISION INTEGER
The fractional seconds precision for datetime data types.
INTERVAL_TYPE CHARACTER VARYING
The data type of interval qualifier for interval data types.
INTERVAL_PRECISION INTEGER
The leading field precision for interval data types.
MAXIMUM_CARDINALITY INTEGER
The maximum cardinality for array data types.
DTD_IDENTIFIER CHARACTER VARYING
The data type identifier to read additional information from
INFORMATION_SCHEMA.ELEMENT_TYPES for array data types,
INFORMATION_SCHEMA.ENUM_VALUES for ENUM data type, and
INFORMATION_SCHEMA.FIELDS for row value data types.
DECLARED_DATA_TYPE CHARACTER VARYING
The declared SQL data type name for numeric data types.
DECLARED_NUMERIC_PRECISION INTEGER
The declared precision, if any, for numeric data types.
DECLARED_NUMERIC_SCALE INTEGER
The declared scale, if any, for numeric data types.
388 of 428
GEOMETRY_TYPE CHARACTER VARYING
The geometry type constraint, if any, for geometry data types.
GEOMETRY_SRID INTEGER
The geometry SRID (Spatial Reference Identifier) constraint, if any, for
geometry data types.
ENUM_VALUES
Contains information about enum values.
FIELDS
Contains information about fields of row values.
389 of 428
OBJECT_TYPE CHARACTER VARYING
The TYPE of the object ('CONSTANT', 'DOMAIN', 'TABLE', or 'ROUTINE').
ROW_IDENTIFIER CHARACTER VARYING
The DTD_IDENTIFIER value of the object.
FIELD_NAME CHARACTER VARYING
The name of the field of the row value.
ORDINAL_POSITION INTEGER
The ordinal position (1-based).
DATA_TYPE CHARACTER VARYING
The SQL data type name.
CHARACTER_MAXIMUM_LENGTH BIGINT
The maximum length in characters for character string data types. For
binary string data types contains the same value as
CHARACTER_OCTET_LENGTH.
CHARACTER_OCTET_LENGTH BIGINT
The maximum length in bytes for binary string data types. For character
string data types contains the same value as
CHARACTER_MAXIMUM_LENGTH.
CHARACTER_SET_CATALOG CHARACTER VARYING
The catalog (database name) for character string data types.
CHARACTER_SET_SCHEMA CHARACTER VARYING
The name of public schema for character string data types.
CHARACTER_SET_NAME CHARACTER VARYING
The 'Unicode' for character string data types.
COLLATION_CATALOG CHARACTER VARYING
The catalog (database name) for character string data types.
COLLATION_SCHEMA CHARACTER VARYING
The name of public schema for character string data types.
COLLATION_NAME CHARACTER VARYING
The name of collation for character string data types.
NUMERIC_PRECISION INTEGER
390 of 428
The precision for numeric data types.
NUMERIC_PRECISION_RADIX INTEGER
The radix of precision (2 or 10) for numeric data types.
NUMERIC_SCALE INTEGER
The scale for numeric data types.
DATETIME_PRECISION INTEGER
The fractional seconds precision for datetime data types.
INTERVAL_TYPE CHARACTER VARYING
The data type of interval qualifier for interval data types.
INTERVAL_PRECISION INTEGER
The leading field precision for interval data types.
MAXIMUM_CARDINALITY INTEGER
The maximum cardinality for array data types.
DTD_IDENTIFIER CHARACTER VARYING
The data type identifier to read additional information from
INFORMATION_SCHEMA.ELEMENT_TYPES for array data types,
INFORMATION_SCHEMA.ENUM_VALUES for ENUM data type, and
INFORMATION_SCHEMA.FIELDS for row value data types.
DECLARED_DATA_TYPE CHARACTER VARYING
The declared SQL data type name for numeric data types.
DECLARED_NUMERIC_PRECISION INTEGER
The declared precision, if any, for numeric data types.
DECLARED_NUMERIC_SCALE INTEGER
The declared scale, if any, for numeric data types.
GEOMETRY_TYPE CHARACTER VARYING
The geometry type constraint, if any, for geometry data types.
GEOMETRY_SRID INTEGER
The geometry SRID (Spatial Reference Identifier) constraint, if any, for
geometry data types.
INDEXES
Contains information about indexes.
391 of 428
INDEX_CATALOG CHARACTER VARYING
The catalog (database name).
INDEX_SCHEMA CHARACTER VARYING
The schema of the index.
INDEX_NAME CHARACTER VARYING
The name of the index.
TABLE_CATALOG CHARACTER VARYING
The catalog (database name).
TABLE_SCHEMA CHARACTER VARYING
The schema of the table.
TABLE_NAME CHARACTER VARYING
The name of the table.
INDEX_TYPE_NAME CHARACTER VARYING
The type of the index ('PRIMARY KEY', 'UNIQUE INDEX', 'SPATIAL INDEX',
etc.)
IS_GENERATED BOOLEAN
Whether index is generated by a constraint and belongs to it.
REMARKS CHARACTER VARYING
Optional remarks.
INDEX_CLASS CHARACTER VARYING
The Java class name of index implementation.
INDEX_COLUMNS
Contains information about columns used in indexes.
392 of 428
TABLE_CATALOG CHARACTER VARYING
The catalog (database name).
TABLE_SCHEMA CHARACTER VARYING
The schema of the table.
TABLE_NAME CHARACTER VARYING
The name of the table.
COLUMN_NAME CHARACTER VARYING
The name of the column.
ORDINAL_POSITION INTEGER
The ordinal position (1-based).
ORDERING_SPECIFICATION CHARACTER VARYING
'ASC' or 'DESC'.
NULL_ORDERING CHARACTER VARYING
'FIRST', 'LAST', or NULL.
IS_UNIQUE BOOLEAN
Whether this column is a part of unique column list of a unique index
(TRUE or FALSE).
INFORMATION_SCHEMA_CATALOG_NAME
Contains a single row with the name of catalog (database name).
IN_DOUBT
Contains information about prepared transactions.
393 of 428
KEY_COLUMN_USAGE
Contains information about columns used by primary key, unique, or
referential constraint.
LOCKS
Contains information about tables locked by sessions.
394 of 428
LOCK_TYPE CHARACTER VARYING
'READ' or 'WRITE'.
PARAMETERS
Contains information about parameters of routines.
395 of 428
CHARACTER_SET_CATALOG CHARACTER VARYING
The catalog (database name) for character string data types.
CHARACTER_SET_SCHEMA CHARACTER VARYING
The name of public schema for character string data types.
CHARACTER_SET_NAME CHARACTER VARYING
The 'Unicode' for character string data types.
COLLATION_CATALOG CHARACTER VARYING
The catalog (database name) for character string data types.
COLLATION_SCHEMA CHARACTER VARYING
The name of public schema for character string data types.
COLLATION_NAME CHARACTER VARYING
The name of collation for character string data types.
NUMERIC_PRECISION INTEGER
The precision for numeric data types.
NUMERIC_PRECISION_RADIX INTEGER
The radix of precision (2 or 10) for numeric data types.
NUMERIC_SCALE INTEGER
The scale for numeric data types.
DATETIME_PRECISION INTEGER
The fractional seconds precision for datetime data types.
INTERVAL_TYPE CHARACTER VARYING
The data type of interval qualifier for interval data types.
INTERVAL_PRECISION INTEGER
The leading field precision for interval data types.
MAXIMUM_CARDINALITY INTEGER
The maximum cardinality for array data types.
DTD_IDENTIFIER CHARACTER VARYING
The data type identifier to read additional information from
INFORMATION_SCHEMA.ELEMENT_TYPES for array data types,
INFORMATION_SCHEMA.ENUM_VALUES for ENUM data type, and
INFORMATION_SCHEMA.FIELDS for row value data types.
396 of 428
DECLARED_DATA_TYPE CHARACTER VARYING
The declared SQL data type name for numeric data types.
DECLARED_NUMERIC_PRECISION INTEGER
The declared precision, if any, for numeric data types.
DECLARED_NUMERIC_SCALE INTEGER
The declared scale, if any, for numeric data types.
PARAMETER_DEFAULT CHARACTER VARYING
NULL.
GEOMETRY_TYPE CHARACTER VARYING
The geometry type constraint, if any, for geometry data types.
GEOMETRY_SRID INTEGER
The geometry SRID (Spatial Reference Identifier) constraint, if any, for
geometry data types.
QUERY_STATISTICS
Contains statistics of queries when query statistics gathering is enabled.
REFERENTIAL_CONSTRAINTS
Contains additional information about referential constraints.
398 of 428
The rule for DELETE in referenced table ('RESTRICT', 'CASCADE', 'SET
DEFAULT', or 'SET NULL').
RIGHTS
Contains information about granted rights and roles.
ROLES
Contains information about roles.
ROUTINES
Contains information about user-defined routines, including aggregate
functions.
399 of 428
The schema of the overloaded version of routine.
SPECIFIC_NAME CHARACTER VARYING
The name of the overloaded version of routine.
ROUTINE_CATALOG CHARACTER VARYING
The catalog (database name).
ROUTINE_SCHEMA CHARACTER VARYING
The schema of the routine.
ROUTINE_NAME CHARACTER VARYING
The name of the routine.
ROUTINE_TYPE CHARACTER VARYING
'PROCEDURE', 'FUNCTION', or 'AGGREGATE'.
DATA_TYPE CHARACTER VARYING
The SQL data type name.
CHARACTER_MAXIMUM_LENGTH BIGINT
The maximum length in characters for character string data types. For
binary string data types contains the same value as
CHARACTER_OCTET_LENGTH.
CHARACTER_OCTET_LENGTH BIGINT
The maximum length in bytes for binary string data types. For character
string data types contains the same value as
CHARACTER_MAXIMUM_LENGTH.
CHARACTER_SET_CATALOG CHARACTER VARYING
The catalog (database name) for character string data types.
CHARACTER_SET_SCHEMA CHARACTER VARYING
The name of public schema for character string data types.
CHARACTER_SET_NAME CHARACTER VARYING
The 'Unicode' for character string data types.
COLLATION_CATALOG CHARACTER VARYING
The catalog (database name) for character string data types.
COLLATION_SCHEMA CHARACTER VARYING
The name of public schema for character string data types.
400 of 428
COLLATION_NAME CHARACTER VARYING
The name of collation for character string data types.
NUMERIC_PRECISION INTEGER
The precision for numeric data types.
NUMERIC_PRECISION_RADIX INTEGER
The radix of precision (2 or 10) for numeric data types.
NUMERIC_SCALE INTEGER
The scale for numeric data types.
DATETIME_PRECISION INTEGER
The fractional seconds precision for datetime data types.
INTERVAL_TYPE CHARACTER VARYING
The data type of interval qualifier for interval data types.
INTERVAL_PRECISION INTEGER
The leading field precision for interval data types.
MAXIMUM_CARDINALITY INTEGER
The maximum cardinality for array data types.
DTD_IDENTIFIER CHARACTER VARYING
The data type identifier to read additional information from
INFORMATION_SCHEMA.ELEMENT_TYPES for array data types,
INFORMATION_SCHEMA.ENUM_VALUES for ENUM data type, and
INFORMATION_SCHEMA.FIELDS for row value data types.
ROUTINE_BODY CHARACTER VARYING
'EXTERNAL'.
ROUTINE_DEFINITION CHARACTER VARYING
Source code or NULL if not applicable or user doesn't have ADMIN
privileges.
EXTERNAL_NAME CHARACTER VARYING
The name of the class or method.
EXTERNAL_LANGUAGE CHARACTER VARYING
'JAVA'.
PARAMETER_STYLE CHARACTER VARYING
401 of 428
'GENERAL'.
IS_DETERMINISTIC CHARACTER VARYING
Whether routine is deterministic ('YES' or 'NO').
DECLARED_DATA_TYPE CHARACTER VARYING
The declared SQL data type name for numeric data types.
DECLARED_NUMERIC_PRECISION INTEGER
The declared precision, if any, for numeric data types.
DECLARED_NUMERIC_SCALE INTEGER
The declared scale, if any, for numeric data types.
GEOMETRY_TYPE CHARACTER VARYING
The geometry type constraint, if any, for geometry data types.
GEOMETRY_SRID INTEGER
The geometry SRID (Spatial Reference Identifier) constraint, if any, for
geometry data types.
REMARKS CHARACTER VARYING
Optional remarks.
SCHEMATA
Contains information about schemas.
SEQUENCES
Contains information about sequences.
403 of 428
The increment value.
CYCLE_OPTION CHARACTER VARYING
Whether values are cycled ('YES' or 'NO').
DECLARED_DATA_TYPE CHARACTER VARYING
The declared SQL data type name for numeric data types.
DECLARED_NUMERIC_PRECISION INTEGER
The declared precision, if any, for numeric data types.
DECLARED_NUMERIC_SCALE INTEGER
The declared scale, if any, for numeric data types.
BASE_VALUE BIGINT
The current base value.
CACHE BIGINT
The cache size.
REMARKS CHARACTER VARYING
Optional remarks.
SESSIONS
Contains information about sessions. Only users with ADMIN privileges can
see all sessions, other users can see only own session.
SESSION_ID INTEGER
The identifier of the session.
USER_NAME CHARACTER VARYING
The name of the user.
SERVER CHARACTER VARYING
The name of the server used by remote connection.
CLIENT_ADDR CHARACTER VARYING
The client address and port used by remote connection.
CLIENT_INFO CHARACTER VARYING
Additional client information provided by remote connection.
SESSION_START TIMESTAMP(9) WITH TIME ZONE
404 of 428
When this session was started.
ISOLATION_LEVEL CHARACTER VARYING
The isolation level of the session ('READ UNCOMMITTED', 'READ
COMMITTED', 'REPEATABLE READ', 'SNAPSHOT', or 'SERIALIZABLE').
EXECUTING_STATEMENT CHARACTER VARYING
The currently executing statement, if any.
EXECUTING_STATEMENT_START TIMESTAMP(9) WITH TIME ZONE
When the current command was started, if any.
CONTAINS_UNCOMMITTED BOOLEAN
Whether the session contains any uncommitted changes.
SESSION_STATE CHARACTER VARYING
The state of the session ('RUNNING', 'SLEEP', etc.)
BLOCKER_ID INTEGER
The identifier or blocking session, if any.
SLEEP_SINCE TIMESTAMP(9) WITH TIME ZONE
When the last command was finished if session is sleeping.
SESSION_STATE
Contains the state of the current session.
SETTINGS
Contains values of various settings.
405 of 428
SYNONYMS
Contains information about table synonyms.
TABLES
Contains information about tables. See also
INFORMATION_SCHEMA.COLUMNS.
406 of 428
IS_INSERTABLE_INTO CHARACTER VARYING
Whether the table is insertable ('YES' or 'NO').
COMMIT_ACTION CHARACTER VARYING
'DELETE', 'DROP', or 'PRESERVE' for temporary tables.
STORAGE_TYPE CHARACTER VARYING
'CACHED' for regular persisted tables, 'MEMORY' for in-memory tables or
persisted tables with in-memory indexes, 'GLOBAL TEMPORARY' or
'LOCAL TEMPORARY' for temporary tables, 'EXTERNAL' for tables with
external table engines, or 'TABLE LINK' for linked tables.
REMARKS CHARACTER VARYING
Optional remarks.
LAST_MODIFICATION BIGINT
The sequence number of the last modification, if applicable.
TABLE_CLASS CHARACTER VARYING
The Java class name of implementation.
ROW_COUNT_ESTIMATE BIGINT
The approximate number of rows if known or some default value if
unknown. For regular tables contains the total number of rows including
the uncommitted rows.
TABLE_CONSTRAINTS
Contains basic information about table constraints (check, primary key,
unique, and referential).
407 of 428
The catalog (database name).
TABLE_SCHEMA CHARACTER VARYING
The schema of the table.
TABLE_NAME CHARACTER VARYING
The name of the table.
IS_DEFERRABLE CHARACTER VARYING
'NO'.
INITIALLY_DEFERRED CHARACTER VARYING
'NO'.
ENFORCED CHARACTER VARYING
'YES' for non-referential constants. 'YES' for referential constants when
checks for referential integrity are enabled for the both referenced and
referencing tables and 'NO' when they are disabled.
INDEX_CATALOG CHARACTER VARYING
The catalog (database name).
INDEX_SCHEMA CHARACTER VARYING
The schema of the index.
INDEX_NAME CHARACTER VARYING
The name of the index.
REMARKS CHARACTER VARYING
Optional remarks.
TABLE_PRIVILEGES
Contains information about privileges of tables. See
INFORMATION_SCHEMA.CHECK_CONSTRAINTS,
INFORMATION_SCHEMA.KEY_COLUMN_USAGE, and
INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS for additional
information.
TRIGGERS
Contains information about triggers.
409 of 428
'ROW' or 'STATEMENT'.
ACTION_TIMING CHARACTER VARYING
'BEFORE', 'AFTER', or 'INSTEAD OF'.
IS_ROLLBACK BOOLEAN
Whether this trigger is executed on rollback.
JAVA_CLASS CHARACTER VARYING
The Java class name.
QUEUE_SIZE INTEGER
The size of the queue (is not actually used).
NO_WAIT BOOLEAN
Whether trigger is defined with NO WAIT clause (is not actually used).
REMARKS CHARACTER VARYING
Optional remarks.
USERS
Contains information about users. Only users with ADMIN privileges can
see all users, other users can see only themselves.
VIEWS
Contains additional information about views. See
INFORMATION_SCHEMA.TABLES for basic information.
410 of 428
TABLE_NAME CHARACTER VARYING
The name of the table.
VIEW_DEFINITION CHARACTER VARYING
The query SQL, if applicable.
CHECK_OPTION CHARACTER VARYING
'NONE'.
IS_UPDATABLE CHARACTER VARYING
'NO'.
INSERTABLE_INTO CHARACTER VARYING
'NO'.
IS_TRIGGER_UPDATABLE CHARACTER VARYING
Whether the view has INSTEAD OF trigger for UPDATE ('YES' or 'NO').
IS_TRIGGER_DELETABLE CHARACTER VARYING
Whether the view has INSTEAD OF trigger for DELETE ('YES' or 'NO').
IS_TRIGGER_INSERTABLE_INTO CHARACTER VARYING
Whether the view has INSTEAD OF trigger for INSERT ('YES' or 'NO').
STATUS CHARACTER VARYING
'VALID' or 'INVALID'.
REMARKS CHARACTER VARYING
Optional remarks.
Range Table
The range table is a dynamic system table that contains all values from a
start to an end value. Non-zero step value may be also specified, default is
1. Start value, end value, and optional step value are converted to BIGINT
data type. The table contains one column called X. If start value is greater
than end value and step is positive the result is empty. If start value is
less than end value and step is negative the result is empty too. If start
value is equal to end value the result contains only start value. Start
value, start value plus step, start value plus step multiplied by two and so
on are included in result. If step is positive the last value is less than or
equal to the specified end value. If step in negative the last value is
411 of 428
greater than or equal to the specified end value. The table is used as
follows:
Examples:
412 of 428
Build
Portability
Environment
Building the Software
Using Maven 2
Using Eclipse
Translating
Submitting Source Code Changes
Reporting Problems or Requests
Automated Build
Generating Railroad Diagrams
Portability
This database is written in Java and therefore works on many platforms.
Environment
To run this database, a Java Runtime Environment (JRE) version 8 or
higher is required.
To create the database executables, the following software stack was
used. To use this database, it is not required to install this software
however.
• Mac OS X and Windows
• Oracle JDK Version 8
• Eclipse
• Eclipse Plugins: Eclipse Checkstyle Plug-in, EclEmma Java Code
Coverage
• Mozilla Firefox
• OpenOffice
• NSIS (Nullsoft Scriptable Install System)
• Maven
build -?
build jar
To run the build tool in shell mode, use the command line option -:
./build.sh -
Using Maven 2
Using a Central Repository
You can include the database in your Maven 2 project as a dependency.
Example:
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>2.1.214</version>
</dependency>
mvn com.edugility.h2-maven-plugin:1.0-SNAPSHOT:spawn
414 of 428
To stop the H2 server, use:
mvn com.edugility.h2-maven-plugin:1.0-SNAPSHOT:stop
build mavenInstallLocal
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
Using Eclipse
To create an Eclipse project for H2, use the following steps:
• Install Git and Eclipse.
• Get the H2 source code from Github:
git clone https://github.com/h2database/h2database
• Download all dependencies:
build.bat download(Windows)
./build.sh download(otherwise)
• In Eclipse, create a new Java project from existing source code: File,
New, Project, Java Project, Create project from existing source.
• Select the h2 folder, click Next and Finish.
• To resolve com.sun.javadoc import statements, you may need to
manually add the file <java.home>/../lib/tools.jar to the build path.
Translating
The translation of this software is split into the following parts:
• H2 Console: src/main/org/h2/server/web/res/_text_*.prop
• Error messages: src/main/org/h2/res/_messages_*.prop
415 of 428
To translate the H2 Console, start it and select Preferences / Translate.
After you are done, send the translated *.prop file to the Google Group.
The web site is currently translated using Google.
417 of 428
Automated Build
This build process is automated and runs regularly. The build process
includes running the tests and code coverage, using the command line
./build.sh jar testCI. The results are available on CI workflow page.
418 of 428
History
Change Log
History of this Database Engine
Why Java
Supporters
Change Log
The up-to-date change log is available here
Why Java
The main reasons to use a Java database are:
• Very simple to integrate in Java applications
• Support for many different platforms
• More secure than native applications (no buffer overflows)
• User defined functions (or triggers) run very fast
• Unicode support
Some think Java is too slow for low level operations, but this is no longer
true. Garbage collection for example is now faster than manual memory
management.
Developing Java code is faster than developing C or C++ code. When
using Java, most time can be spent on improving the algorithms instead of
porting the code to different platforms or doing memory management.
Features such as Unicode and network libraries are already built-in. In
Java, writing secure code is easier because buffer overflows can not occur.
Features such as reflection can be used for randomized testing.
419 of 428
Java is future proof: a lot of companies support Java. Java is now open
source.
To increase the portability and ease of use, this software depends on very
few libraries. Features that are not available in open source Java
implementations (such as Swing) are not used, or only used for optional
features.
Supporters
Many thanks for those who reported bugs, gave valuable feedback, spread
the word, and translated this project.
Also many thanks to the donors. To become a donor, use PayPal (at the
very bottom of the main web page). Donators are:
• Martin Wildam, Austria
• tagtraum industries incorporated, USA
• TimeWriter, Netherlands
• Cognitect, USA
• Code 42 Software, Inc., Minneapolis
• Code Lutin, France
• NetSuxxess GmbH, Germany
• Poker Copilot, Steve McLeod, Germany
• SkyCash, Poland
• Lumber-mill, Inc., Japan
• StockMarketEye, USA
• Eckenfelder GmbH & Co.KG, Germany
• Jun Iyama, Japan
• Steven Branda, USA
• Anthony Goubard, Netherlands
• Richard Hickey, USA
• Alessio Jacopo D'Adamo, Italy
• Ashwin Jayaprakash, USA
• Donald Bleyl, USA
• Frank Berger, Germany
• Florent Ramiere, France
• Antonio Casqueiro, Portugal
• Oliver Computing LLC, USA
• Harpal Grover Consulting Inc., USA
• Elisabetta Berlini, Italy
420 of 428
• William Gilbert, USA
• Antonio Dieguez Rojas, Chile
• Ontology Works, USA
• Pete Haidinyak, USA
• William Osmond, USA
• Joachim Ansorg, Germany
• Oliver Soerensen, Germany
• Christos Vasilakis, Greece
• Fyodor Kupolov, Denmark
• Jakob Jenkov, Denmark
• Stéphane Chartrand, Switzerland
• Glenn Kidd, USA
• Gustav Trede, Sweden
• Joonas Pulakka, Finland
• Bjorn Darri Sigurdsson, Iceland
• Gray Watson, USA
• Erik Dick, Germany
• Pengxiang Shao, China
• Bilingual Marketing Group, USA
• Philippe Marschall, Switzerland
• Knut Staring, Norway
• Theis Borg, Denmark
• Mark De Mendonca Duske, USA
• Joel A. Garringer, USA
• Olivier Chafik, France
• Rene Schwietzke, Germany
• Jalpesh Patadia, USA
• Takanori Kawashima, Japan
• Terrence JC Huang, China
• JiaDong Huang, Australia
• Laurent van Roy, Belgium
• Qian Chen, China
• Clinton Hyde, USA
• Kritchai Phromros, Thailand
• Alan Thompson, USA
• Ladislav Jech, Czech Republic
• Dimitrijs Fedotovs, Latvia
• Richard Manley-Reeve, United Kingdom
421 of 428
• Daniel Cyr, ThirdHalf.com, LLC, USA
• Peter Jünger, Germany
• Dan Keegan, USA
• Rafel Israels, Germany
• Fabien Todescato, France
• Cristan Meijer, Netherlands
• Adam McMahon, USA
• Fábio Gomes Lisboa Gomes, Brasil
• Lyderic Landry, England
• Mederp, Morocco
• Joaquim Golay, Switzerland
• Clemens Quoss, Germany
• Kervin Pierre, USA
• Jake Bellotti, Australia
• Arun Chittanoor, USA
422 of 428
Frequently Asked Questions
I Have a Problem or Feature Request
Are there Known Bugs? When is the Next Release?
Is this Database Engine Open Source?
Is Commercial Support Available?
How to Create a New Database?
How to Connect to a Database?
Where are the Database Files Stored?
What is the Size Limit (Maximum Size) of a Database?
Is it Reliable?
Why is Opening my Database Slow?
My Query is Slow
H2 is Very Slow
Column Names are Incorrect?
Float is Double?
How to Translate this Project?
How to Contribute to this Project?
423 of 428
RENCES=false. A known workaround is to put the h2*.jar file in a
shared lib directory (common/lib). Tomcat 8.5 and newer versions
don't clear fields and don't have such property.
• Some problems have been found with right outer join. Internally, it is
converted to left outer join, which does not always produce the same
results as other databases when used in combination with other
joins. This problem is fixed in H2 version 1.3.
For a complete list, see Open Issues.
Is it Reliable?
That is not easy to say. It is still a quite new product. A lot of tests have
been written, and the code coverage of these tests is higher than 80% for
each package. Randomized stress tests are run regularly. But there are
probably still bugs that have not yet been found (as with most software).
Some features are known to be dangerous, they are only supported for
situations where performance is more important than reliability. Those
dangerous features are:
• Disabling the transaction log or FileDescriptor.sync() using LOG=0 or
LOG=1.
• Using the transaction isolation level READ_UNCOMMITTED
(LOCK_MODE 0) while at the same time using multiple connections.
• Disabling database file protection using (setting FILE_LOCK to NO in
the database URL).
• Disabling referential integrity using SET REFERENTIAL_INTEGRITY
FALSE.
In addition to that, running out of memory should be avoided. In older
versions, OutOfMemory errors while using the database could corrupt a
databases.
This database is well tested using automated test cases. The tests run
every night and run for more than one hour. But not all areas of this
database are equally well tested. When using one of the following features
for production, please ensure your use case is well tested (if possible with
automated test cases). The areas that are not well tested are:
• Platforms other than Windows, Linux, Mac OS X, or runtime
environments other than Oracle / OpenJDK 7, 8, 9.
• The features AUTO_SERVER and AUTO_RECONNECT.
• Cluster mode, 2-phase commit, savepoints.
• Fulltext search.
425 of 428
• Operations on LOBs over 2 GB.
• The optimizer may not always select the best plan.
• Using the ICU4J collator.
Areas considered experimental are:
• The PostgreSQL server
• Clustering (there are cases were transaction isolation can be broken
due to timing issues, for example one session overtaking another
session).
• Compatibility modes for other databases (only some features are
implemented).
• The soft reference cache (CACHE_TYPE=SOFT_LRU). It might not
improve performance, and out of memory issues have been reported.
Some users have reported that after a power failure, the database cannot
be opened sometimes. In this case, use a backup of the database or the
Recover tool. Please report such problems. The plan is that the database
automatically recovers in all situations.
My Query is Slow
Slow SELECT (or DELETE, UPDATE, MERGE) statement can have multiple
reasons. Follow this checklist:
• Run ANALYZE (see documentation for details).
• Run the query with EXPLAIN and check if indexes are used (see
documentation for details).
• If required, create additional indexes and try again using ANALYZE
and EXPLAIN.
• If it doesn't help please report the problem.
426 of 428
H2 is Very Slow
By default, H2 closes the database when the last connection is closed. If
your application closes the only connection after each operation, the
database is opened and closed a lot, which is quite slow. There are
multiple ways to solve this problem, see Database Performance Tuning.
Float is Double?
For a table defined as CREATE TABLE TEST(X FLOAT) the method
ResultSet.getObject() returns a java.lang.Double, I expect it to return a
java.lang.Float. What's wrong?
This is not a bug. According the JDBC specification, the JDBC data type
FLOAT is equivalent to DOUBLE, and both are mapped to java.lang.Double.
See also Mapping SQL and Java Types - 8.3.10 FLOAT.
Use REAL or FLOAT(24) data type for java.lang.Float values.
428 of 428