Debian Codegraph @

src/docsrc/html/performance.html

raw
1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
2 <!--
3 Copyright 2004-2023 H2 Group. Multiple-Licensed under the MPL 2.0,
4 and the EPL 1.0 (https://h2database.com/html/license.html).
5 Initial Developer: H2 Group
6 -->
7 <html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
8 <head>
9 <meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
10 <meta name="viewport" content="width=device-width, initial-scale=1" />
11 <title>
12 Performance
13 </title>
14 <link rel="stylesheet" type="text/css" href="stylesheet.css" />
15 <!-- [search] { -->
16 <script type="text/javascript" src="navigation.js"></script>
17 </head><body onload="frameMe();">
18 <table class="content"><tr class="content"><td class="content"><div class="contentDiv">
19 <!-- } -->
20
21 <h1>Performance</h1>
22 <a href="#performance_comparison">
23 Performance Comparison</a><br />
24 <a href="#poleposition_benchmark">
25 PolePosition Benchmark</a><br />
26 <a href="#database_performance_tuning">
27 Database Performance Tuning</a><br />
28 <a href="#built_in_profiler">
29 Using the Built-In Profiler</a><br />
30 <a href="#application_profiling">
31 Application Profiling</a><br />
32 <a href="#database_profiling">
33 Database Profiling</a><br />
34 <a href="#explain_plan">
35 Statement Execution Plans</a><br />
36 <a href="#storage_and_indexes">
37 How Data is Stored and How Indexes Work</a><br />
38 <a href="#fast_import">
39 Fast Database Import</a><br />
40
41 <h2 id="performance_comparison">Performance Comparison</h2>
42 <p>
43 In many cases H2 is faster than other
44 (open source and not open source) database engines.
45 Please note this is mostly a single connection benchmark run on one computer,
46 with many very simple operations running against the database.
47 This benchmark does not include very complex queries.
48 The embedded mode of H2 is faster than the client-server mode because
49 the per-statement overhead is greatly reduced.
50 </p>
51
52 <h3>Embedded</h3>
53 <table class="main">
54 <tr><th>Test Case</th><th>Unit</th><th>H2</th><th>HSQLDB</th><th>Derby</th></tr>
55 <tr><td>Simple: Init</td><td>ms</td><td>1021</td><td>2510</td><td>6762</td></tr>
56 <tr><td>Simple: Query (random)</td><td>ms</td><td>513</td><td>653</td><td>2035</td></tr>
57 <tr><td>Simple: Query (sequential)</td><td>ms</td><td>1344</td><td>2210</td><td>7665</td></tr>
58 <tr><td>Simple: Update (sequential)</td><td>ms</td><td>1642</td><td>3040</td><td>7034</td></tr>
59 <tr><td>Simple: Delete (sequential)</td><td>ms</td><td>1697</td><td>2310</td><td>9981</td></tr>
60 <tr><td>Simple: Memory Usage</td><td>MB</td><td>18</td><td>15</td><td>13</td></tr>
61 <tr><td>BenchA: Init</td><td>ms</td><td>801</td><td>2877</td><td>6576</td></tr>
62 <tr><td>BenchA: Transactions</td><td>ms</td><td>1369</td><td>2629</td><td>4987</td></tr>
63 <tr><td>BenchA: Memory Usage</td><td>MB</td><td>12</td><td>15</td><td>9</td></tr>
64 <tr><td>BenchB: Init</td><td>ms</td><td>966</td><td>2544</td><td>7161</td></tr>
65 <tr><td>BenchB: Transactions</td><td>ms</td><td>341</td><td>2316</td><td>815</td></tr>
66 <tr><td>BenchB: Memory Usage</td><td>MB</td><td>14</td><td>10</td><td>10</td></tr>
67 <tr><td>BenchC: Init</td><td>ms</td><td>2630</td><td>3144</td><td>7420</td></tr>
68 <tr><td>BenchC: Transactions</td><td>ms</td><td>1732</td><td>1742</td><td>2735</td></tr>
69 <tr><td>BenchC: Memory Usage</td><td>MB</td><td>19</td><td>34</td><td>11</td></tr>
70 <tr><td>Executed statements</td><td>#</td><td>2222032</td><td>2222032</td><td>2222032</td></tr>
71 <tr><td>Total time</td><td>ms</td><td>14056</td><td>25975</td><td>63171</td></tr>
72 <tr><td>Statements per second</td><td>#/s</td><td>158084</td><td>85545</td><td>35174</td></tr>
73 </table>
74
75 <h3>Client-Server</h3>
76 <table class="main">
77 <tr><th>Test Case</th><th>Unit</th><th>H2</th><th>HSQLDB</th><th>Derby</th><th>PostgreSQL</th><th>MySQL</th></tr>
78 <tr><td>Simple: Init</td><td>ms</td><td>27989</td><td>48055</td><td>47142</td><td>32972</td><td>109482</td></tr>
79 <tr><td>Simple: Query (random)</td><td>ms</td><td>4821</td><td>5984</td><td>14741</td><td>4089</td><td>15140</td></tr>
80 <tr><td>Simple: Query (sequential)</td><td>ms</td><td>33656</td><td>49112</td><td>95999</td><td>35676</td><td>143536</td></tr>
81 <tr><td>Simple: Update (sequential)</td><td>ms</td><td>9878</td><td>23565</td><td>31418</td><td>26113</td><td>50676</td></tr>
82 <tr><td>Simple: Delete (sequential)</td><td>ms</td><td>13056</td><td>28584</td><td>43955</td><td>20985</td><td>64647</td></tr>
83 <tr><td>Simple: Memory Usage</td><td>MB</td><td>18</td><td>15</td><td>15</td><td>2</td><td>4</td></tr>
84 <tr><td>BenchA: Init</td><td>ms</td><td>20993</td><td>42525</td><td>38335</td><td>27794</td><td>107723</td></tr>
85 <tr><td>BenchA: Transactions</td><td>ms</td><td>16549</td><td>29255</td><td>28995</td><td>23113</td><td>65036</td></tr>
86 <tr><td>BenchA: Memory Usage</td><td>MB</td><td>12</td><td>18</td><td>11</td><td>1</td><td>4</td></tr>
87 <tr><td>BenchB: Init</td><td>ms</td><td>26785</td><td>48772</td><td>39756</td><td>32369</td><td>115398</td></tr>
88 <tr><td>BenchB: Transactions</td><td>ms</td><td>898</td><td>10046</td><td>1916</td><td>818</td><td>1794</td></tr>
89 <tr><td>BenchB: Memory Usage</td><td>MB</td><td>16</td><td>11</td><td>12</td><td>2</td><td>5</td></tr>
90 <tr><td>BenchC: Init</td><td>ms</td><td>18266</td><td>26865</td><td>39325</td><td>24547</td><td>70531</td></tr>
91 <tr><td>BenchC: Transactions</td><td>ms</td><td>6569</td><td>7783</td><td>9412</td><td>8916</td><td>19150</td></tr>
92 <tr><td>BenchC: Memory Usage</td><td>MB</td><td>17</td><td>35</td><td>13</td><td>2</td><td>7</td></tr>
93 <tr><td>Executed statements</td><td>#</td><td>2222032</td><td>2222032</td><td>2222032</td><td>2222032</td><td>2222032</td></tr>
94 <tr><td>Total time</td><td>ms</td><td>179460</td><td>320546</td><td>390994</td><td>237392</td><td>763113</td></tr>
95 <tr><td>Statements per second</td><td>#/s</td><td>12381</td><td>6932</td><td>5683</td><td>9360</td><td>2911</td></tr>
96 </table>
97
98 <h3>Benchmark Results and Comments</h3>
99
100 <h4>H2</h4>
101 <p>
102 Version 2.0.202 (2021-11-25) was used for the test.
103 For most operations, the performance of H2 is about the same as for HSQLDB.
104 One situation where H2 is slow is large result sets, because they are buffered to
105 disk if more than a certain number of records are returned.
106 The advantage of buffering is: there is no limit on the result set size.
107 </p>
108
109 <h4>HSQLDB</h4>
110 <p>
111 Version 2.5.1 was used for the test.
112 Cached tables are used in this test (<code>hsqldb.default_table_type=cached</code>),
113 and the write delay is 1 second (<code>SET WRITE_DELAY 1</code>).
114 </p>
115
116 <h4>Derby</h4>
117 <p>
118 Version 10.14.2.0 was used for the test. Derby is clearly the slowest embedded database in this test.
119 This seems to be a structural problem, because all operations are really slow.
120 It will be hard for the developers of Derby to improve the performance to a reasonable level.
121 A few problems have been identified: leaving autocommit on is a problem for Derby.
122 If it is switched off during the whole test, the results are about 20% better for Derby.
123 Derby calls <code>FileChannel.force(false)</code>, but only twice per log file (not on each commit).
124 Disabling this call improves performance for Derby by about 2%.
125 Unlike H2, Derby does not call <code>FileDescriptor.sync()</code> on each checkpoint.
126 Derby supports a testing mode (system property <code>derby.system.durability=test</code>)
127 where durability is disabled. According to the documentation, this setting should be used for testing only,
128 as the database may not recover after a crash. Enabling this setting improves performance
129 by a factor of 2.6 (embedded mode) or 1.4 (server mode). Even if enabled, Derby is still less
130 than half as fast as H2 in default mode.
131 </p>
132
133 <h4>PostgreSQL</h4>
134 <p>
135 Version 13.4 was used for the test.
136 The following options where changed in <code>postgresql.conf:
137 fsync = off, commit_delay = 100000</code> (microseconds).
138 PostgreSQL is run in server mode.
139 The memory usage number is incorrect, because only the memory usage of the JDBC driver is measured.
140 </p>
141
142 <h4>MySQL</h4>
143 <p>
144 Version 8.0.27 was used for the test.
145 MySQL was run with the InnoDB backend.
146 The setting <code>innodb_flush_log_at_trx_commit</code> and <code>sync_binlog</code>code>
147 (found in the <code>my.ini / community-mysql-server.cnf</code> file) was set to 0. Otherwise
148 (and by default), MySQL is slow (around 140 statements per second in this test)
149 because it tries to flush the data to disk for each commit.
150 For small transactions (when autocommit is on) this is really slow.
151 But many use cases use small or relatively small transactions.
152 Too bad this setting is not listed in the configuration wizard,
153 and it always overwritten when using the wizard.
154 You need to change those settings manually in the file <code>my.ini / community-mysql-server.cnf</code>,
155 and then restart the service.
156 The memory usage number is incorrect, because only the memory usage of the JDBC driver is measured.
157 </p>
158
159 <h4>SQLite</h4>
160 <p>
161 SQLite 3.36.0.3, configured to use <a href="https://sqlite.org/wal.html">WAL</a> and with
162 <a href="https://sqlite.org/pragma.html#pragma_synchronous"><code>synchronous=NORMAL</code></a> was tested in a
163 separate, less reliable run. A rough estimate is that SQLite performs approximately 2-5x worse in the simple benchmarks,
164 which perform simple work in the database, resulting in a low work-per-transaction ratio. SQLite becomes competitive as
165 the complexity of the database interactions increases. The results seemed to vary drastically across machine, and more
166 reliable results should be obtained. Benchmark on your production hardware.
167 </p>
168 <p>
169 The benchmarks used include multi-threaded scenarios, and we were not able to get the SQLite JDBC driver we used to work
170 with them. Help with configuring the driver for multi-threaded usage is welcome.
171 </p>
172
173 <h4>Firebird</h4>
174 <p>
175 Firebird 3.0 (default installation) was tested, but failed on multi-threaded part of the test.
176 It is likely possible to run the performance test with the Firebird database,
177 and any information on how to configure Firebird for this are welcome.
178 </p>
179
180 <h4>Why Oracle / MS SQL Server / DB2 are Not Listed</h4>
181 <p>
182 The license of these databases does not allow to publish benchmark results.
183 This doesn't mean that they are fast. They are in fact quite slow,
184 and need a lot of memory. But you will need to test this yourself.
185 </p>
186
187 <h3>About this Benchmark</h3>
188
189 <h4>How to Run</h4>
190 <p>
191 This test was as follows:
192 </p>
193 <pre>
194 build benchmark
195 </pre>
196
197 <h4>Separate Process per Database</h4>
198 <p>
199 For each database, a new process is started, to ensure the previous test does not impact
200 the current test.
201 </p>
202
203 <h4>Number of Connections</h4>
204 <p>
205 This is mostly a single-connection benchmark.
206 BenchB uses multiple connections; the other tests use one connection.
207 </p>
208
209 <h4>Real-World Tests</h4>
210 <p>
211 Good benchmarks emulate real-world use cases. This benchmark includes 4 test cases:
212 BenchSimple uses one table and many small updates / deletes.
213 BenchA is similar to the TPC-A test, but single connection / single threaded (see also: www.tpc.org).
214 BenchB is similar to the TPC-B test, using multiple connections (one thread per connection).
215 BenchC is similar to the TPC-C test, but single connection / single threaded.
216 </p>
217
218 <h4>Comparing Embedded with Server Databases</h4>
219 <p>
220 This is mainly a benchmark for embedded databases (where the application runs in the same
221 virtual machine as the database engine). However MySQL and PostgreSQL are not Java
222 databases and cannot be embedded into a Java application.
223 For the Java databases, both embedded and server modes are tested.
224 </p>
225
226 <h4>Test Platform</h4>
227 <p>
228 This test is run on Fedora v.34 with Oracle JVM 1.8 and SSD drive.
229 </p>
230
231 <h4>Multiple Runs</h4>
232 <p>
233 When a Java benchmark is run first, the code is not fully compiled and
234 therefore runs slower than when running multiple times. A benchmark
235 should always run the same test multiple times and ignore the first run(s).
236 This benchmark runs three times, but only the last run is measured.
237 </p>
238
239 <h4>Memory Usage</h4>
240 <p>
241 It is not enough to measure the time taken, the memory usage is important as well.
242 Performance can be improved by using a bigger cache, but the amount of memory is limited.
243 HSQLDB tables are kept fully in memory by default; this benchmark
244 uses 'disk based' tables for all databases.
245 Unfortunately, it is not so easy to calculate the memory usage of PostgreSQL
246 and MySQL, because they run in a different process than the test. This benchmark currently
247 does not print memory usage of those databases.
248 </p>
249
250 <h4>Delayed Operations</h4>
251 <p>
252 Some databases delay some operations (for example flushing the buffers)
253 until after the benchmark is run. This benchmark waits between
254 each database tested, and each database runs in a different process (sequentially).
255 </p>
256
257 <h4>Transaction Commit / Durability</h4>
258 <p>
259 Durability means transaction committed to the database will not be lost.
260 Some databases (for example MySQL) try to enforce this by default by
261 calling <code>fsync()</code> to flush the buffers, but
262 most hard drives don't actually flush all data. Calling the method slows down transaction commit a lot,
263 but doesn't always make data durable. When comparing the results, it is important to
264 think about the effect. Many database suggest to 'batch' operations when possible.
265 This benchmark switches off autocommit when loading the data, and calls commit after each 1000
266 inserts. However many applications need 'short' transactions at runtime (a commit after each update).
267 This benchmark commits after each update / delete in the simple benchmark, and after each
268 business transaction in the other benchmarks. For databases that support delayed commits,
269 a delay of one second is used.
270 </p>
271
272 <h4>Using Prepared Statements</h4>
273 <p>
274 Wherever possible, the test cases use prepared statements.
275 </p>
276
277 <h4>Currently Not Tested: Startup Time</h4>
278 <p>
279 The startup time of a database engine is important as well for embedded use.
280 This time is not measured currently.
281 Also, not tested is the time used to create a database and open an existing database.
282 Here, one (wrapper) connection is opened at the start,
283 and for each step a new connection is opened and then closed.
284 </p>
285
286 <h2 id="poleposition_benchmark">PolePosition Benchmark</h2>
287 <p>
288 The PolePosition is an open source benchmark. The algorithms are all quite simple.
289 It was developed / sponsored by db4o.
290 This test was not run for a longer time, so please be aware that the results below
291 are for older database versions (H2 version 1.1, HSQLDB 1.8, Java 1.4).
292 </p>
293 <table class="main">
294 <tr><th>Test Case</th><th>Unit</th><th>H2</th><th>HSQLDB</th><th>MySQL</th></tr>
295 <tr><td>Melbourne write</td><td>ms</td><td>369</td><td>249</td><td>2022</td></tr>
296 <tr><td>Melbourne read</td><td>ms</td><td>47</td><td>49</td><td>93</td></tr>
297 <tr><td>Melbourne read_hot</td><td>ms</td><td>24</td><td>43</td><td>95</td></tr>
298 <tr><td>Melbourne delete</td><td>ms</td><td>147</td><td>133</td><td>176</td></tr>
299 <tr><td>Sepang write</td><td>ms</td><td>965</td><td>1201</td><td>3213</td></tr>
300 <tr><td>Sepang read</td><td>ms</td><td>765</td><td>948</td><td>3455</td></tr>
301 <tr><td>Sepang read_hot</td><td>ms</td><td>789</td><td>859</td><td>3563</td></tr>
302 <tr><td>Sepang delete</td><td>ms</td><td>1384</td><td>1596</td><td>6214</td></tr>
303 <tr><td>Bahrain write</td><td>ms</td><td>1186</td><td>1387</td><td>6904</td></tr>
304 <tr><td>Bahrain query_indexed_string</td><td>ms</td><td>336</td><td>170</td><td>693</td></tr>
305 <tr><td>Bahrain query_string</td><td>ms</td><td>18064</td><td>39703</td><td>41243</td></tr>
306 <tr><td>Bahrain query_indexed_int</td><td>ms</td><td>104</td><td>134</td><td>678</td></tr>
307 <tr><td>Bahrain update</td><td>ms</td><td>191</td><td>87</td><td>159</td></tr>
308 <tr><td>Bahrain delete</td><td>ms</td><td>1215</td><td>729</td><td>6812</td></tr>
309 <tr><td>Imola retrieve</td><td>ms</td><td>198</td><td>194</td><td>4036</td></tr>
310 <tr><td>Barcelona write</td><td>ms</td><td>413</td><td>832</td><td>3191</td></tr>
311 <tr><td>Barcelona read</td><td>ms</td><td>119</td><td>160</td><td>1177</td></tr>
312 <tr><td>Barcelona query</td><td>ms</td><td>20</td><td>5169</td><td>101</td></tr>
313 <tr><td>Barcelona delete</td><td>ms</td><td>388</td><td>319</td><td>3287</td></tr>
314 <tr><td>Total</td><td>ms</td><td>26724</td><td>53962</td><td>87112</td></tr>
315 </table>
316 <p>
317 There are a few problems with the PolePosition test:
318 </p>
319 <ul><li>
320 HSQLDB uses in-memory tables by default while H2 uses persistent tables. The HSQLDB version
321 included in PolePosition does not support changing this, so you need to replace
322 <code>poleposition-0.20/lib/hsqldb.jar</code> with a newer version (for example
323 <code>hsqldb-1.8.0.7.jar</code>),
324 and then use the setting
325 <code>hsqldb.connecturl=jdbc:hsqldb:file:data/hsqldb/dbbench2;hsqldb.default_table_type=cached;sql.enforce_size=true</code>
326 in the file <code>Jdbc.properties</code>.
327 </li><li>HSQLDB keeps the database open between tests, while H2 closes the database (losing all the cache).
328 To change that, use the database URL <code>jdbc:h2:file:data/h2/dbbench;DB_CLOSE_DELAY=-1</code>
329 </li><li>The amount of cache memory is quite important, specially for the PolePosition test.
330 Unfortunately, the PolePosition test does not take this into account.
331 </li></ul>
332
333 <h2 id="database_performance_tuning">Database Performance Tuning</h2>
334
335 <h3>Keep Connections Open or Use a Connection Pool</h3>
336 <p>
337 If your application opens and closes connections a lot (for example, for each request),
338 you should consider using a <a href="tutorial.html#connection_pool">connection pool</a>.
339 Opening a connection using <code>DriverManager.getConnection</code> is specially slow
340 if the database is closed. By default the database is closed if the last connection is closed.
341 </p><p>
342 If you open and close connections a lot but don't want to use a connection pool,
343 consider keeping a 'sentinel' connection open for as long as the application runs,
344 or use delayed database closing. See also
345 <a href="features.html#closing_a_database">Closing a database</a>.
346 </p>
347
348 <h3>Use a Modern JVM</h3>
349 <p>
350 Newer JVMs are faster. Upgrading to the latest version of your JVM can provide a "free" boost to performance.
351 Switching from the default Client JVM to the Server JVM using the <code>-server</code> command-line
352 option improves performance at the cost of a slight increase in start-up time.
353 </p>
354
355 <h3>Virus Scanners</h3>
356 <p>
357 Some virus scanners scan files every time they are accessed.
358 It is very important for performance that database files are not scanned for viruses.
359 The database engine never interprets the data stored in the files as programs,
360 that means even if somebody would store a virus in a database file, this would
361 be harmless (when the virus does not run, it cannot spread).
362 Some virus scanners allow to exclude files by suffix. Ensure files ending with <code>.db</code> are not scanned.
363 </p>
364
365 <h3>Using the Trace Options</h3>
366 <p>
367 If the performance hot spots are in the database engine, in many cases the performance
368 can be optimized by creating additional indexes, or changing the schema. Sometimes the
369 application does not directly generate the SQL statements, for example if an O/R mapping tool
370 is used. To view the SQL statements and JDBC API calls, you can use the trace options.
371 For more information, see <a href="features.html#trace_options">Using the Trace Options</a>.
372 </p>
373
374 <h3>Index Usage</h3>
375 <p>
376 This database uses indexes to improve the performance of
377 <code>SELECT, UPDATE, DELETE</code>.
378 If a column is used in the <code>WHERE</code> clause of a query, and if an index exists on this column,
379 then the index can be used. Multi-column indexes are used if all or the first columns of the index are used.
380 Both equality lookup and range scans are supported.
381 Indexes are used to order result sets, but only if the condition uses the same index or no index at all.
382 The results are sorted in memory if required.
383 Indexes are created automatically for primary key and unique constraints.
384 Indexes are also created for foreign key constraints, if required.
385 For other columns, indexes need to be created manually using the <code>CREATE INDEX</code> statement.
386 </p>
387
388 <h3>Index Hints</h3>
389 <p>
390 If you have determined that H2 is not using the optimal index for your query, you can use index hints to force
391 H2 to use specific indexes.
392 </p>
393 <pre>
394 SELECT * FROM TEST USE INDEX (index_name_1, index_name_2) WHERE X=1
395 </pre>
396 <p>Only indexes in the list will be used when choosing an index to use on the given table. There
397 is no significance to order in this list.
398 </p><p>
399 It is possible that no index in the list is chosen, in which case a full table scan will be used.
400 </p>
401 <p>An empty list of index names forces a full table scan to be performed.</p>
402 <p>Each index in the list must exist.</p>
403
404 <h3>How Data is Stored Internally</h3>
405 <p>
406 For persistent databases, if a table is created with a single column primary key of type <code>BIGINT, INT, SMALLINT, TINYINT</code>,
407 then the data of the table is organized in this way. This is sometimes also called a "clustered index" or
408 "index organized table".
409 </p><p>
410 H2 internally stores table data and indexes in the form of b-trees.
411 Each b-tree stores entries as a list of unique keys (one or more columns) and data (zero or more columns).
412 The table data is always organized in the form of a "data b-tree" with a single column key of type <code>long</code>.
413 If a single column primary key of type <code>BIGINT, INT, SMALLINT, TINYINT</code> is specified when creating the table
414 (or just after creating the table, but before inserting any rows),
415 then this column is used as the key of the data b-tree.
416 If no primary key has been specified, if the primary key column is of another data type,
417 or if the primary key contains more than one column,
418 then a hidden identity column of type <code>BIGINT</code> is added to the table,
419 which is used as the key for the data b-tree.
420 All other columns of the table are stored within the data area of this data b-tree
421 (except for large <code>BLOB, CLOB</code> columns, which are stored externally).
422 </p><p>
423 For each additional index, one new "index b-tree" is created. The key of this b-tree consists of the indexed columns,
424 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
425 contains multiple column, or if the primary key is not of the data types listed above, then the primary key
426 is stored in a new index b-tree.
427 </p>
428
429 <h3>Optimizer</h3>
430 <p>
431 This database uses a cost based optimizer. For simple and queries and queries with medium complexity
432 (less than 7 tables in the join), the expected cost (running time) of all possible plans is calculated,
433 and the plan with the lowest cost is used. For more complex queries, the algorithm first tries
434 all possible combinations for the first few tables, and the remaining tables added using a greedy algorithm
435 (this works well for most joins). Afterwards a genetic algorithm is used to test at most 2000 distinct plans.
436 Only left-deep plans are evaluated.
437 </p>
438
439 <h3>Expression Optimization</h3>
440 <p>
441 After the statement is parsed, all expressions are simplified automatically if possible. Operations
442 are evaluated only once if all parameters are constant. Functions are also optimized, but only
443 if the function is constant (always returns the same result for the same parameter values).
444 If the <code>WHERE</code> clause is always false, then the table is not accessed at all.
445 </p>
446
447 <h3>COUNT(*) Optimization</h3>
448 <p>
449 If the query only counts all rows of a table, then the data is not accessed.
450 However, this is only possible if no <code>WHERE</code> clause is used, that means it only works for
451 queries of the form <code>SELECT COUNT(*) FROM table</code>.
452 </p>
453
454 <h3>Updating Optimizer Statistics / Column Selectivity</h3>
455 <p>
456 When executing a query, at most one index per join can be used.
457 If the same table is joined multiple times, for each join only one index is used
458 (the same index could be used for both joins, or each join could use a different index).
459 Example: for the query
460 <code>SELECT * FROM TEST T1, TEST T2 WHERE T1.NAME='A' AND T2.ID=T1.ID</code>,
461 two index can be used, in this case the index on NAME for T1 and the index on ID for T2.
462 </p><p>
463 If a table has multiple indexes, sometimes more than one index could be used.
464 Example: if there is a table <code>TEST(ID, NAME, FIRSTNAME)</code> and an index on each column,
465 then two indexes could be used for the query <code>SELECT * FROM TEST WHERE NAME='A' AND FIRSTNAME='B'</code>,
466 the index on NAME or the index on FIRSTNAME. It is not possible to use both indexes at the same time.
467 Which index is used depends on the selectivity of the column. The selectivity describes the 'uniqueness' of
468 values in a column. A selectivity of 100 means each value appears only once, and a selectivity of 1 means
469 the same value appears in many or most rows. For the query above, the index on NAME should be used
470 if the table contains more distinct names than first names.
471 </p><p>
472 The SQL statement <code>ANALYZE</code> can be used to automatically estimate the selectivity of the columns in the tables.
473 This command should be run from time to time to improve the query plans generated by the optimizer.
474 </p>
475
476 <h3>In-Memory (Hash) Indexes</h3>
477 <p>
478 Using in-memory indexes, specially in-memory hash indexes, can speed up
479 queries and data manipulation.
480 </p>
481 <p>In-memory indexes are automatically used
482 for in-memory databases, but can also be created for persistent databases
483 using <code>CREATE MEMORY TABLE</code>. In many cases,
484 the rows itself will also be kept in-memory. Please note this may cause memory
485 problems for large tables.
486 </p>
487 <p>
488 In-memory hash indexes are backed by a hash table and are usually faster than
489 regular indexes. However, hash indexes only supports direct lookup (<code>WHERE ID = ?</code>)
490 but not range scan (<code>WHERE ID &lt; ?</code>). To use hash indexes, use HASH as in:
491 <code>CREATE UNIQUE HASH INDEX</code> and
492 <code>CREATE TABLE ...(ID INT PRIMARY KEY HASH,...)</code>.
493 </p>
494
495 <h3>Use Prepared Statements</h3>
496 <p>
497 If possible, use prepared statements with parameters.
498 </p>
499
500 <h3>Prepared Statements and IN(...)</h3>
501 <p>
502 Avoid generating SQL statements with a variable size IN(...) list.
503 Instead, use a prepared statement with arrays as in the following example:
504 </p>
505 <pre>
506 PreparedStatement prep = conn.prepareStatement(
507 "SELECT * FROM TEST WHERE ID = ANY(?)");
508 prep.setObject(1, new Long[] { 1L, 2L });
509 ResultSet rs = prep.executeQuery();
510 </pre>
511
512 <h3>Optimization Examples</h3>
513 <p>
514 See <code>src/test/org/h2/samples/optimizations.sql</code> for a few examples of queries
515 that benefit from special optimizations built into the database.
516 </p>
517
518 <h3>Cache Size and Type</h3>
519 <p>
520 By default the cache size of H2 is quite small. Consider using a larger cache size, or enable
521 the second level soft reference cache. See also <a href="features.html#cache_settings">Cache Settings</a>.
522 </p>
523
524 <h3>Data Types</h3>
525 <p>
526 Each data type has different storage and performance characteristics:
527 </p>
528 <ul><li>The <code>DECIMAL/NUMERIC</code> type is slower
529 and requires more storage than the <code>REAL</code> and <code>DOUBLE PRECISION</code> types.
530 </li><li>Text types are slower to read, write, and compare than numeric types and generally require more storage.
531 </li><li>See <a href="advanced.html#large_objects">Large Objects</a> for information on
532 <code>BINARY</code> vs. <code>BLOB</code>
533 and <code>VARCHAR</code> vs. <code>CLOB</code> performance.
534 </li><li>Parsing and formatting takes longer for the
535 <code>TIME</code>, <code>DATE</code>, and
536 <code>TIMESTAMP</code> types than the numeric types.
537 </li><li><code>SMALLINT/TINYINT/BOOLEAN</code> are not significantly smaller or faster
538 to work with than <code>INTEGER</code> in most modes.
539 </li></ul>
540
541 <h3>Sorted Insert Optimization</h3>
542 <p>
543 To reduce disk space usage and speed up table creation, an
544 optimization for sorted inserts is available. When used, b-tree pages
545 are split at the insertion point. To use this optimization, add <code>SORTED</code>
546 before the <code>SELECT</code> statement:
547 </p>
548 <pre>
549 CREATE TABLE TEST(ID INT PRIMARY KEY, NAME VARCHAR) AS
550 SORTED SELECT X, SPACE(100) FROM SYSTEM_RANGE(1, 100);
551 INSERT INTO TEST
552 SORTED SELECT X, SPACE(100) FROM SYSTEM_RANGE(101, 200);
553 </pre>
554
555 <h2 id="built_in_profiler">Using the Built-In Profiler</h2>
556 <p>
557 A very simple Java profiler is built-in. To use it, use the following template:
558 </p>
559 <pre>
560 import org.h2.util.Profiler;
561 Profiler prof = new Profiler();
562 prof.startCollecting();
563 // .... some long running process, at least a few seconds
564 prof.stopCollecting();
565 System.out.println(prof.getTop(3));
566 </pre>
567
568 <h2 id="application_profiling">Application Profiling</h2>
569
570 <h3>Analyze First</h3>
571 <p>
572 Before trying to optimize performance, it is important to understand where the problem is (what part of the application is slow).
573 Blind optimization or optimization based on guesses should be avoided, because usually it is not an efficient strategy.
574 There are various ways to analyze an application. Sometimes two implementations can be compared using
575 <code>System.currentTimeMillis()</code>. But this does not work for complex applications with many modules, and for memory problems.
576 </p>
577 <p>
578 A simple way to profile an application is to use the built-in profiling tool of java. Example:
579 </p>
580 <pre>
581 java -Xrunhprof:cpu=samples,depth=16 com.acme.Test
582 </pre>
583 <p>
584 Unfortunately, it is only possible to profile the application from start to end. Another solution is to create
585 a number of full thread dumps. To do that, first run <code>jps -l</code> to get the process id, and then
586 run <code>jstack &lt;pid&gt;</code> or <code>kill -QUIT &lt;pid&gt;</code> (Linux) or press
587 Ctrl+C (Windows).
588 </p>
589 <p>
590 A simple profiling tool is included in H2. To use it, the application needs to be changed slightly. Example:
591 </p>
592 <pre>
593 import org.h2.util;
594 ...
595 Profiler profiler = new Profiler();
596 profiler.startCollecting();
597 // application code
598 System.out.println(profiler.getTop(3));
599 </pre>
600 <p>
601 The profiler is built into the H2 Console tool, to analyze databases that open slowly.
602 To use it, run the H2 Console, and then click on 'Test Connection'.
603 Afterwards, click on "Test successful" and you get the most common stack traces,
604 which helps to find out why it took so long to connect. You will only get the stack traces
605 if opening the database took more than a few seconds.
606 </p>
607
608 <h2 id="database_profiling">Database Profiling</h2>
609 <p>
610 The <code>ConvertTraceFile</code> tool generates SQL statement statistics at the end of the SQL script file.
611 The format used is similar to the profiling data generated when using <code>java -Xrunhprof</code>.
612 For this to work, the trace level needs to be 2 or higher (<code>TRACE_LEVEL_FILE=2</code>).
613 The easiest way to set the trace level is to append the setting to the database URL, for example:
614 <code>jdbc:h2:~/test;TRACE_LEVEL_FILE=2</code> or <code>jdbc:h2:tcp://localhost/~/test;TRACE_LEVEL_FILE=2</code>.
615 As an example, execute the following script using the H2 Console:
616 </p>
617 <pre>
618 SET TRACE_LEVEL_FILE 2;
619 DROP TABLE IF EXISTS TEST;
620 CREATE TABLE TEST(ID INT PRIMARY KEY, NAME VARCHAR(255));
621 @LOOP 1000 INSERT INTO TEST VALUES(?, ?);
622 SET TRACE_LEVEL_FILE 0;
623 </pre>
624 <p>
625 After running the test case, convert the <code>.trace.db</code> file using the <code>ConvertTraceFile</code> tool.
626 The trace file is located in the same directory as the database file.
627 </p>
628 <pre>
629 java -cp h2*.jar org.h2.tools.ConvertTraceFile
630 -traceFile "~/test.trace.db" -script "~/test.sql"
631 </pre>
632 <p>
633 The generated file <code>test.sql</code> will contain the SQL statements as well as the
634 following profiling data (results vary):
635 </p>
636 <pre>
637 -----------------------------------------
638 -- SQL Statement Statistics
639 -- time: total time in milliseconds (accumulated)
640 -- count: how many times the statement ran
641 -- result: total update count or row count
642 -----------------------------------------
643 -- self accu time count result sql
644 -- 62% 62% 158 1000 1000 INSERT INTO TEST VALUES(?, ?);
645 -- 37% 100% 93 1 0 CREATE TABLE TEST(ID INT PRIMARY KEY...
646 -- 0% 100% 0 1 0 DROP TABLE IF EXISTS TEST;
647 -- 0% 100% 0 1 0 SET TRACE_LEVEL_FILE 3;
648 </pre>
649
650 <h2 id="explain_plan">Statement Execution Plans</h2>
651 <p>
652 The SQL statement <code>EXPLAIN</code> displays the indexes and optimizations the database uses for a statement.
653 The following statements support <code>EXPLAIN</code>: <code>SELECT, UPDATE, DELETE, MERGE, INSERT</code>.
654 The following query shows that the database uses the primary key index to search for rows:
655 </p>
656 <pre>
657 EXPLAIN SELECT * FROM TEST WHERE ID=1;
658 SELECT
659 TEST.ID,
660 TEST.NAME
661 FROM PUBLIC.TEST
662 /* PUBLIC.PRIMARY_KEY_2: ID = 1 */
663 WHERE ID = 1
664 </pre>
665 <p>
666 For joins, the tables in the execution plan are sorted in the order they are processed.
667 The following query shows the database first processes the table <code>INVOICE</code> (using the primary key).
668 For each row, it will additionally check that the value of the column <code>AMOUNT</code> is larger than zero,
669 and for those rows the database will search in the table <code>CUSTOMER</code> (using the primary key).
670 The query plan contains some redundancy so it is a valid statement.
671 </p>
672 <pre>
673 CREATE TABLE CUSTOMER(ID IDENTITY, NAME VARCHAR);
674 CREATE TABLE INVOICE(ID IDENTITY,
675 CUSTOMER_ID INT REFERENCES CUSTOMER(ID),
676 AMOUNT NUMBER);
677
678 EXPLAIN SELECT I.ID, C.NAME FROM CUSTOMER C, INVOICE I
679 WHERE I.ID=10 AND AMOUNT>0 AND C.ID=I.CUSTOMER_ID;
680
681 SELECT
682 I.ID,
683 C.NAME
684 FROM PUBLIC.INVOICE I
685 /* PUBLIC.PRIMARY_KEY_9: ID = 10 */
686 /* WHERE (I.ID = 10)
687 AND (AMOUNT > 0)
688 */
689 INNER JOIN PUBLIC.CUSTOMER C
690 /* PUBLIC.PRIMARY_KEY_5: ID = I.CUSTOMER_ID */
691 ON 1=1
692 WHERE (C.ID = I.CUSTOMER_ID)
693 AND ((I.ID = 10)
694 AND (AMOUNT > 0))
695 </pre>
696
697 <h3>Displaying the Scan Count</h3>
698 <p>
699 <code>EXPLAIN ANALYZE</code> additionally shows the scanned rows per table and pages read from disk per table or index.
700 This will actually execute the query, unlike <code>EXPLAIN</code> which only prepares it.
701 The following query scanned 1000 rows, and to do that had to read 85 pages from the data area of the table.
702 Running the query twice will not list the pages read from disk, because they are now in the cache.
703 The <code>tableScan</code> means this query doesn't use an index.
704 </p>
705 <pre>
706 EXPLAIN ANALYZE SELECT * FROM TEST;
707 SELECT
708 TEST.ID,
709 TEST.NAME
710 FROM PUBLIC.TEST
711 /* PUBLIC.TEST.tableScan */
712 /* scanCount: 1000 */
713 /*
714 total: 85
715 TEST.TEST_DATA read: 85 (100%)
716 */
717 </pre>
718 <p>
719 The cache will prevent the pages are read twice. H2 reads all columns of the row
720 unless only the columns in the index are read. Except for large CLOB and BLOB, which are not store in the table.
721 </p>
722
723 <h3>Special Optimizations</h3>
724 <p>
725 For certain queries, the database doesn't need to read all rows, or doesn't need to sort the result even if <code>ORDER BY</code> is used.
726 </p><p>
727 For queries of the form <code>SELECT COUNT(*), MIN(ID), MAX(ID) FROM TEST</code>, the query plan includes the line
728 <code>/* direct lookup */</code> if the data can be read from an index.
729 </p><p>
730 For queries of the form <code>SELECT DISTINCT CUSTOMER_ID FROM INVOICE</code>, the query plan includes the line
731 <code>/* distinct */</code> if there is an non-unique or multi-column index on this column, and if this column has a low selectivity.
732 </p><p>
733 For queries of the form <code>SELECT * FROM TEST ORDER BY ID</code>, the query plan includes the line
734 <code>/* index sorted */</code> to indicate there is no separate sorting required.
735 </p><p>
736 For queries of the form <code>SELECT * FROM TEST GROUP BY ID ORDER BY ID</code>, the query plan includes the line
737 <code>/* group sorted */</code> to indicate there is no separate sorting required.
738 </p>
739
740 <h2 id="storage_and_indexes">How Data is Stored and How Indexes Work</h2>
741 <p>
742 Internally, each row in a table is identified by a unique number, the row id.
743 The rows of a table are stored with the row id as the key.
744 The row id is a number of type long.
745 If a table has a single column primary key of type <code>INT</code> or <code>BIGINT</code>,
746 then the value of this column is the row id, otherwise the database generates the row id automatically.
747 There is a (non-standard) way to access the row id: using the <code>_ROWID_</code> pseudo-column:
748 </p>
749 <pre>
750 CREATE TABLE ADDRESS(FIRST_NAME VARCHAR,
751 NAME VARCHAR, CITY VARCHAR, PHONE VARCHAR);
752 INSERT INTO ADDRESS VALUES('John', 'Miller', 'Berne', '123 456 789');
753 INSERT INTO ADDRESS VALUES('Philip', 'Jones', 'Berne', '123 012 345');
754 SELECT _ROWID_, * FROM ADDRESS;
755 </pre>
756 <p>
757 The data is stored in the database as follows:
758 </p>
759 <table>
760 <tr><th>_ROWID_</th><th>FIRST_NAME</th><th>NAME</th><th>CITY</th><th>PHONE</th></tr>
761 <tr><td>1</td><td>John</td><td>Miller</td><td>Berne</td><td>123 456 789</td></tr>
762 <tr><td>2</td><td>Philip</td><td>Jones</td><td>Berne</td><td>123 012 345</td></tr>
763 </table>
764 <p>
765 Access by row id is fast because the data is sorted by this key.
766 Please note the row id is not available until after the row was added
767 (that means, it can not be used in generated columns or constraints).
768 If the query condition does not contain the row id (and if no other index can be used), then all rows of the table are scanned.
769 A table scan iterates over all rows in the table, in the order of the row id.
770 To find out what strategy the database uses to retrieve the data, use <code>EXPLAIN SELECT</code>:
771 </p>
772 <pre>
773 SELECT * FROM ADDRESS WHERE NAME = 'Miller';
774
775 EXPLAIN SELECT PHONE FROM ADDRESS WHERE NAME = 'Miller';
776 SELECT
777 PHONE
778 FROM PUBLIC.ADDRESS
779 /* PUBLIC.ADDRESS.tableScan */
780 WHERE NAME = 'Miller';
781 </pre>
782
783 <h3>Indexes</h3>
784 <p>
785 An index internally is basically just a table that contains the indexed column(s), plus the row id:
786 </p>
787 <pre>
788 CREATE INDEX INDEX_PLACE ON ADDRESS(CITY, NAME, FIRST_NAME);
789 </pre>
790 <p>
791 In the index, the data is sorted by the indexed columns.
792 So this index contains the following data:
793 </p>
794 <table>
795 <tr><th>CITY</th><th>NAME</th><th>FIRST_NAME</th><th>_ROWID_</th></tr>
796 <tr><td>Berne</td><td>Jones</td><td>Philip</td><td>2</td></tr>
797 <tr><td>Berne</td><td>Miller</td><td>John</td><td>1</td></tr>
798 </table>
799 <p>
800 When the database uses an index to query the data, it searches the index for the given data,
801 and (if required) reads the remaining columns in the main data table (retrieved using the row id).
802 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.
803 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).
804 This index is also used when reading all rows, sorted by the indexed columns.
805 However, if only the first name is known, then this index is not used:
806 </p>
807 <pre>
808 EXPLAIN SELECT PHONE FROM ADDRESS
809 WHERE CITY = 'Berne' AND NAME = 'Miller'
810 AND FIRST_NAME = 'John';
811 SELECT
812 PHONE
813 FROM PUBLIC.ADDRESS
814 /* PUBLIC.INDEX_PLACE: FIRST_NAME = 'John'
815 AND CITY = 'Berne'
816 AND NAME = 'Miller'
817 */
818 WHERE (FIRST_NAME = 'John')
819 AND ((CITY = 'Berne')
820 AND (NAME = 'Miller'));
821
822 EXPLAIN SELECT PHONE FROM ADDRESS WHERE CITY = 'Berne';
823 SELECT
824 PHONE
825 FROM PUBLIC.ADDRESS
826 /* PUBLIC.INDEX_PLACE: CITY = 'Berne' */
827 WHERE CITY = 'Berne';
828
829 EXPLAIN SELECT * FROM ADDRESS ORDER BY CITY, NAME, FIRST_NAME;
830 SELECT
831 ADDRESS.FIRST_NAME,
832 ADDRESS.NAME,
833 ADDRESS.CITY,
834 ADDRESS.PHONE
835 FROM PUBLIC.ADDRESS
836 /* PUBLIC.INDEX_PLACE */
837 ORDER BY 3, 2, 1
838 /* index sorted */;
839
840 EXPLAIN SELECT PHONE FROM ADDRESS WHERE FIRST_NAME = 'John';
841 SELECT
842 PHONE
843 FROM PUBLIC.ADDRESS
844 /* PUBLIC.ADDRESS.tableScan */
845 WHERE FIRST_NAME = 'John';
846 </pre>
847 <p>
848 If your application often queries the table for a phone number, then it makes sense to create
849 an additional index on it:
850 </p>
851 <pre>
852 CREATE INDEX IDX_PHONE ON ADDRESS(PHONE);
853 </pre>
854 <p>
855 This index contains the phone number, and the row id:
856 </p>
857 <table>
858 <tr><th>PHONE</th><th>_ROWID_</th></tr>
859 <tr><td>123 012 345</td><td>2</td></tr>
860 <tr><td>123 456 789</td><td>1</td></tr>
861 </table>
862
863 <h3>Using Multiple Indexes</h3>
864 <p>
865 Within a query, only one index per logical table is used.
866 Using the condition <code>PHONE = '123 567 789' OR CITY = 'Berne'</code>
867 would use a table scan instead of first using the index on the phone number and then the index on the city.
868 It makes sense to write two queries and combine then using <code>UNION</code>.
869 In this case, each individual query uses a different index:
870 </p>
871 <pre>
872 EXPLAIN SELECT NAME FROM ADDRESS WHERE PHONE = '123 567 789'
873 UNION SELECT NAME FROM ADDRESS WHERE CITY = 'Berne';
874
875 (SELECT
876 NAME
877 FROM PUBLIC.ADDRESS
878 /* PUBLIC.IDX_PHONE: PHONE = '123 567 789' */
879 WHERE PHONE = '123 567 789')
880 UNION
881 (SELECT
882 NAME
883 FROM PUBLIC.ADDRESS
884 /* PUBLIC.INDEX_PLACE: CITY = 'Berne' */
885 WHERE CITY = 'Berne')
886 </pre>
887
888 <h2 id="fast_import">Fast Database Import</h2>
889 <p>
890 If you have to import a lot of rows, use a PreparedStatement or use CSV import.
891 Please note that <code>CREATE TABLE(...) ... AS SELECT ...</code>
892 is faster than <code>CREATE TABLE(...); INSERT INTO ... SELECT ...</code>.
893 </p>
894
895 <!-- [close] { --></div></td></tr></table><!-- } --><!-- analytics --></body></html>