reference_en.html 399.4 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108
<!DOCTYPE html>
<html>
    <head>
        <meta charset='UTF-8' />
        <title>ClickHouse Guide</title>

<style type='text/css'>

/*
@font-face {
	font-family:'textbook';
	src:local('textbook');
	src:url(https://yastatic.net/metrika/1.59.743/bower_components/islands-romochka/desktop.blocks/i-font/_face/i-font_face_textbook.woff),
		url(https://yastatic.net/metrika/1.59.743/bower_components/islands-romochka/desktop.blocks/i-font/_face/i-font_face_textbook.ttf);
}

@font-face {
	font-family:'Yandex Sans Text Web';
	src:url(https://yastatic.net/adv-www/_/yy5JveR58JFkc97waf-xp0i6_jM.eot);
	src:url(https://yastatic.net/adv-www/_/yy5JveR58JFkc97waf-xp0i6_jM.eot?#iefix) format('embedded-opentype'),
		url(https://yastatic.net/adv-www/_/CYblzLEXzCqQIvrYs7QKQe2omRk.woff2) format('woff2'),
		url(https://yastatic.net/adv-www/_/pUcnOdRwl83MvPPzrNomhyletnA.woff) format('woff'),
		url(https://yastatic.net/adv-www/_/vNFEmXOcGYKJ4AAidUprHWoXrLU.ttf) format('truetype'),
		url(https://yastatic.net/adv-www/_/0w7OcWZM_QLP8x-LQUXFOgXO6dE.svg#YandexSansTextWeb-Bold) format('svg');
	font-weight:700;
	font-style:normal;
	font-stretch:normal
}

@font-face {
	font-family:'Yandex Sans Text Web';
	src:url(https://yastatic.net/adv-www/_/LI6l3L2RqcgxBe2pXmuUha37czQ.eot);
	src:url(https://yastatic.net/adv-www/_/LI6l3L2RqcgxBe2pXmuUha37czQ.eot?#iefix) format('embedded-opentype'),
		url(https://yastatic.net/adv-www/_/z3MYElcut0R2MF_Iw1RDNrstgYs.woff2) format('woff2'),
		url(https://yastatic.net/adv-www/_/1jvKJ_-hCXl3s7gmFl-y_-UHTaI.woff) format('woff'),
		url(https://yastatic.net/adv-www/_/9nzjfpCR2QHvK1EzHpDEIoVFGuY.ttf) format('truetype'),
		url(https://yastatic.net/adv-www/_/gwyBTpxSwkFCF1looxqs6JokKls.svg#YandexSansTextWeb-Regular) format('svg');
	font-weight:400;
	font-style:normal;
	font-stretch:normal
}

@font-face {
	font-family:'Yandex Sans Text Web';
		src:url(https://yastatic.net/adv-www/_/ayAFYoY8swgBLhq_I56tKj2JftU.eot);
		src:url(https://yastatic.net/adv-www/_/ayAFYoY8swgBLhq_I56tKj2JftU.eot?#iefix) format('embedded-opentype'),
			url(https://yastatic.net/adv-www/_/lGQcYklLVV0hyvz1HFmFsUTj8_0.woff2) format('woff2'),
			url(https://yastatic.net/adv-www/_/f0AAJ9GJ4iiwEmhG-7PWMHk6vUY.woff) format('woff'),
			url(https://yastatic.net/adv-www/_/4UDe4nlVvgEJ-VmLWNVq3SxCsA.ttf) format('truetype'),
			url(https://yastatic.net/adv-www/_/EKLr1STNokPqxLAQa_RyN82pL98.svg#YandexSansTextWeb-Light) format('svg');
	font-weight:300;
	font-style:normal;
	font-stretch:normal
}
*/
@font-face {
	font-family:'Yandex Sans Display Web';
	src:url(https://yastatic.net/adv-www/_/H63jN0veW07XQUIA2317lr9UIm8.eot);
	src:url(https://yastatic.net/adv-www/_/H63jN0veW07XQUIA2317lr9UIm8.eot?#iefix) format('embedded-opentype'),
			url(https://yastatic.net/adv-www/_/sUYVCPUAQE7ExrvMS7FoISoO83s.woff2) format('woff2'),
			url(https://yastatic.net/adv-www/_/v2Sve_obH3rKm6rKrtSQpf-eB7U.woff) format('woff'),
			url(https://yastatic.net/adv-www/_/PzD8hWLMunow5i3RfJ6WQJAL7aI.ttf) format('truetype'),
			url(https://yastatic.net/adv-www/_/lF_KG5g4tpQNlYIgA0e77fBSZ5s.svg#YandexSansDisplayWeb-Regular) format('svg');
	font-weight:400;
	font-style:normal;
	font-stretch:normal
}
/*
@font-face {
	font-family:'Yandex Sans Display Web';
	src:url(https://yastatic.net/adv-www/_/g8_MyyKVquSZ3xEL6tarK__V9Vw.eot);
	src:url(https://yastatic.net/adv-www/_/g8_MyyKVquSZ3xEL6tarK__V9Vw.eot?#iefix) format('embedded-opentype'),
			url(https://yastatic.net/adv-www/_/LGiRvlfqQHlWR9YKLhsw5e7KGNA.woff2) format('woff2'),
			url(https://yastatic.net/adv-www/_/40vXwNl4eYYMgteIVgLP49dwmfc.woff) format('woff'),
			url(https://yastatic.net/adv-www/_/X6zG5x_wO8-AtwJ-vDLJcKC5228.ttf) format('truetype'),
			url(https://yastatic.net/adv-www/_/ZKhaR0m08c8CRRL77GtFKoHcLYA.svg#YandexSansDisplayWeb-Light) format('svg');
	font-weight:300;
	font-style:normal;
	font-stretch:normal
}*/

body {
    background-color: #DEF;

    background-image: linear-gradient(bottom, rgb(255,238,204) 17%, rgb(115,255,250) 54%, rgb(176,216,255) 77%);
    background-image: -o-linear-gradient(bottom, rgb(255,238,204) 17%, rgb(115,255,250) 54%, rgb(176,216,255) 77%);
    background-image: -moz-linear-gradient(bottom, rgb(255,238,204) 17%, rgb(115,255,250) 54%, rgb(176,216,255) 77%);
    background-image: -webkit-linear-gradient(bottom, rgb(255,238,204) 17%, rgb(115,255,250) 54%, rgb(176,216,255) 77%);
    background-image: -ms-linear-gradient(bottom, rgb(255,238,204) 17%, rgb(115,255,250) 54%, rgb(176,216,255) 77%);

    background-image: -webkit-gradient(
        linear,
        left bottom,
        left top,
        color-stop(0.17, rgb(255,238,204)),
        color-stop(0.54, rgb(115,255,250)),
        color-stop(0.77, rgb(176,216,255))
    );

    font-family: Arial, sans-serif;
    font-size: 14px;
}

h1 {
    margin: 0;
    font-family: 'Yandex Sans Display Web', Arial, sans-serif;
}

A
Alexey Milovidov 已提交
109 110 111 112 113 114 115 116 117
h2 {
    font-family: 'Yandex Sans Display Web', Arial, sans-serif;
}

h3 {
    font-family: 'Yandex Sans Display Web', Arial, sans-serif;
}


118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276
p {
    line-height: 20px;
    white-space: pre-wrap;
}

a {
    text-decoration: none;
    color: #06F;
}

a:hover {
    text-decoration: underline;
    color: #F40;
}

.island {
    background-color: #FFF;
    box-shadow: 0 0 0 1px rgba(0, 0, 0, 0.1), 0 8px 25px -5px rgba(0, 0, 0, 0.25);
/*    border-radius: 5px;*/
    padding: 10px;
    width: 1000px;
    margin: 10px auto 10px auto;
}

.title {
    font-size: 100px;
    font-weight: normal;
    text-align: center;
    margin: 0;
}

.subtitle {
    font-size: 50px;
    font-weight: normal;
    text-align: center;
    margin: 0;
    font-family: 'Yandex Sans Display Web', Arial, sans-serif;
}

.signature {
    text-align: right;
    margin: 0;
}

.terminal {
    font-family: Monospace;
    font-size: 9pt;
    color: #B2B2B2;
    background-color: #000;
    padding: 3px;
    border: 1px solid #AAA;
    white-space: pre-wrap;
}

.text-example {
    font-family: Monospace;
    font-size: 9pt;
    background-color: #FEC;
    padding: 3px;
    border: 1px solid #DDD;
    white-space: pre-wrap;
}

.inline-example {
    font-family: Monospace;
    font-size: 9pt;
    background-color: #FEC;
}

.informer {
    width: 1000px;
    margin: 20px auto 10px auto;
    text-align: right;
}

.show-example {
    display: none;
}

.show-hide-link {
    color: #06C;
    border-bottom: 1px dotted #06C;
}

.show-hide-link:hover {
    color: #F40;
    border-bottom: 1px dotted #F40;
    cursor: pointer;
}

.head-anchor {
    float: right;
    color: #AAA;
}

.head-anchor:hover {
    text-decoration: none;
}

#contents {
    line-height: 20px;
}

.contents-element {
}


/* Цвета в терминале */

i.c0  { font-style: normal; color: #000000; }
i.c1  { font-style: normal; color: #B21818; }
i.c2  { font-style: normal; color: #18B218; }
i.c3  { font-style: normal; color: #B26818; }
i.c4  { font-style: normal; color: #1818B2; }
i.c5  { font-style: normal; color: #B218B2; }
i.c6  { font-style: normal; color: #18B2B2; }
i.c7  { font-style: normal; color: #B2B2B2; }
i.c8  { font-style: normal; color: #686868; font-weight: bold; }
i.c9  { font-style: normal; color: #FF5454; font-weight: bold; }
i.c10 { font-style: normal; color: #54FF54; font-weight: bold; }
i.c11 { font-style: normal; color: #FFFF54; font-weight: bold; }
i.c12 { font-style: normal; color: #5454FF; font-weight: bold; }
i.c13 { font-style: normal; color: #FF54FF; font-weight: bold; }
i.c14 { font-style: normal; color: #54FFFF; font-weight: bold; }
i.c15 { font-style: normal; color: #FFFFFF; font-weight: bold; }

</style>

    </head>
    <body>

<script type="text/javascript">
function getParams() {
    var matches = document.cookie.match(/yandex_login=([\w\-]+)/);
    return (matches && matches.length == 2) ? { "login": matches[1] } : {};
}
</script>

<!-- Yandex.Metrica counter -->
<script src="https://mc.yandex.ru/metrika/watch.js" type="text/javascript"></script>
<script type="text/javascript">
try { var yaCounter18343495 = new Ya.Metrika({id:18343495,
          webvisor:true,
          clickmap:true,
          trackLinks:true,
          accurateTrackBounce:true,
          trackHash:true,
          params: getParams()});
} catch(e) { }
</script>
<noscript><div><img src="https://mc.yandex.ru/watch/18343495" style="position:absolute; left:-9999px;" alt=" " /></div></noscript>
<!-- /Yandex.Metrica counter -->

<script type="text/javascript" src="https://yandex.st/jquery/1.7.2/jquery.min.js"></script>

<div class='island'>

<div style="float: right; margin-left: -100%; margin-top: 3px; margin-right: 3px;">
	<div style="display: inline-block; width: 50px; text-align: center; margin-right: 2px;">
277
	<a href='reference_ru.html' title='In russian'>
278 279 280 281 282 283 284 285 286 287
		<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 10 6" width="50" height="30" style="border: 1px solid #AAA;">
			<rect fill="#fff" width="10" height="3"/>
			<rect fill="#d52b1e" y="3" width="10" height="3"/>
			<rect fill="#0039a6" y="2" width="10" height="2"/>
		</svg>
	Russian
	</a>
	</div>

	<div style="display: inline-block; width: 50px; text-align: center; margin-left: 2px;">
288
	<a href='reference_en.html' title='In english'>
289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322
		<svg xmlns="http://www.w3.org/2000/svg" width="50" height="30" viewBox="0,0 25,15" style="border: 1px solid #AAA;">
			<rect width="25" height="15" fill="#00247d"/>
			<path d="M 0,0 L 25,15 M 25,0 L 0,15" stroke="#fff" stroke-width="3"/>
			<path d="M 12.5,0 V 15 M 0,7.5 H 25" stroke="#fff" stroke-width="5"/>
			<path d="M 12.5,0 V 15 M 0,7.5 H 25" stroke="#cf142b" stroke-width="3"/>
		</svg>
	English
	</a>
	</div>
</div>

<h1 class='title not-for-contents'>ClickHouse</h1>
<h2 class='subtitle not-for-contents'>Reference Manual</h2>
<div class='signature'> — Alexey Milovidov</div>
</div>

<div class='island'>
<h1>Contents</h1>
<br />
<div id='contents'></div>
</div>

<div class='island'>
<h1>Introduction</h1>
</div>

<div class='island'>
<h2>What is ClickHouse?</h2>
<p>ClickHouse is a columnar DBMS for OLAP.
</p>
<p>In a &quot;normal&quot; row-oriented DBMS, data is stored in this order:
</p>

<pre class='text-example'>
323
5123456789123456789     1       Eurobasket - Greece - Bosnia and Herzegovina - example.com      1       2011-09-01 01:03:02     6274717   1294101174      11409   612345678912345678      0       33      6       http://www.example.com/basketball/team/123/match/456789.html http://www.example.com/basketball/team/123/match/987654.html       0       1366    768     32      10      3183      0       0       13      0\0     1       1       0       0                       2011142 -1      0               0       01321     613     660     2011-09-01 08:01:17     0       0       0       0       utf-8   1466    0       0       0       5678901234567890123               277789954       0       0       0       0       0
324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569
5234985259563631958     0       Consulting, Tax assessment, Accounting, Law       1       2011-09-01 01:03:02     6320881   2111222333      213     6458937489576391093     0       3       2       http://www.example.ru/         0       800     600       16      10      2       153.1   0       0       10      63      1       1       0       0                       2111678 000       0       588     368     240     2011-09-01 01:03:17     4       0       60310   0       windows-1251    1466    0       000               778899001       0       0       0       0       0
...
</pre>

<p>In order words, all the values related to a row are stored next to each other. Examples of a row-oriented DBMS are MySQL, Postgres, MS SQL Server, and others.
</p>
<p>In a column-oriented DBMS, data is stored like this:
</p>

<pre class='text-example' style='white-space: pre; overflow-x: hidden'>
<b>WatchID:</b>    5385521489354350662     5385521490329509958     5385521489953706054     5385521490476781638     5385521490583269446     5385521490218868806     5385521491437850694   5385521491090174022      5385521490792669254     5385521490420695110     5385521491532181574     5385521491559694406     5385521491459625030     5385521492275175494   5385521492781318214      5385521492710027334     5385521492955615302     5385521493708759110     5385521494506434630     5385521493104611398
<b>JavaEnable:</b> 1       0       1       0       0       0       1       0       1       1       1       1       1       1       0       1       0       0       1       1
<b>Title:</b>      Yandex  Announcements - Investor Relations - Yandex     Yandex — Contact us — Moscow    Yandex — Mission        Ru      Yandex — History — History of Yandex    Yandex Financial Releases - Investor Relations - Yandex Yandex — Locations      Yandex Board of Directors - Corporate Governance - Yandex       Yandex — Technologies
<b>GoodEvent:</b>  1       1       1       1       1       1       1       1       1       1       1       1       1       1       1       1       1       1       1       1
<b>EventTime:</b>  2016-05-18 05:19:20     2016-05-18 08:10:20     2016-05-18 07:38:00     2016-05-18 01:13:08     2016-05-18 00:04:06     2016-05-18 04:21:30     2016-05-18 00:34:16     2016-05-18 07:35:49     2016-05-18 11:41:59     2016-05-18 01:13:32
...
</pre>

<p>These examples only show the order that data is arranged in.
The values from different columns are stored separately, and data from the same column is stored together.
Examples of a column-oriented DBMS: Vertica, Paraccel (Actian Matrix) (Amazon Redshift), Sybase IQ, Exasol, Infobright, InfiniDB, MonetDB (VectorWise) (Actian Vector), LucidDB, SAP HANA, Google Dremel, Google PowerDrill, Metamarkets Druid, kdb+ and others.
</p>

<p>Different orders for storing data are better suited to different scenarios.
The data access scenario refers to what queries are made, how often, and in what proportion; how much data is read for each type of query - rows, columns, and bytes; the relationship between reading and updating data; the working size of the data and how locally it is used; whether transactions are used, and how isolated they are; requirements for data replication and logical integrity; requirements for latency and throughput for each type of query, and so on.
</p>
<p>The higher the load on the system, the more important it is to customize the system to the scenario, and the more specific this customization becomes. There is no system that is equally well-suited to significantly different scenarios. If a system is adaptable to a wide set of scenarios, under a high load, the system will handle all the scenarios equally poorly, or will work well for just one of the scenarios.
</p>
<p>We&#39;ll say that the following is true for the OLAP (online analytical processing) scenario:
- The vast majority of requests are for read access.
- Data is updated in fairly large batches (> 1000 rows), not by single rows; or it is not updated at all.
- Data is added to the DB but is not modified.
- For reads, quite a large number of rows are extracted from the DB, but only a small subset of columns.
- Tables are &quot;wide,&quot; meaning they contain a large number of columns.
- Queries are relatively rare (usually hundreds of queries per server or less per second).
- For simple queries, latencies around 50 ms are allowed.
- Column values are fairly small -  numbers and short strings (for example, 60 bytes per URL).
- Requires high throughput when processing a single query (up to billions of rows per second per server).
- There are no transactions.
- Low requirements for data consistency.
- There is one large table per query. All tables are small, except for one.
- A query result is significantly smaller than the source data. That is, data is filtered or aggregated. The result fits in a single server&#39;s RAM.
</p>
<p>It is easy to see that the OLAP scenario is very different from other popular scenarios (such as OLTP or Key-Value access). So it doesn&#39;t make sense to try to use OLTP or a Key-Value DB for processing analytical queries if you want to get decent performance. For example, if you try to use MongoDB or Elliptics for analytics, you will get very poor performance compared to OLAP databases.
</p>
<p>Columnar-oriented databases are better suited to OLAP scenarios (at least 100 times better in processing speed for most queries), for the following reasons:
</p>
<p>1. For I/O.
1.1. For an analytical query, only a small number of table columns need to be read. In a column-oriented database, you can read just the data you need. For example, if you need 5 columns out of 100, you can expect a 20-fold reduction in I/O.
1.2. Since data is read in packets, it is easier to compress. Data in columns is also easier to compress. This further reduces the I/O volume.
1.3. Due to the reduced I/O, more data fits in the system cache.
</p>
<p>For example, the query &quot;count the number of records for each advertising platform&quot; requires reading one &quot;advertising platform ID&quot; column, which takes up 1 byte uncompressed. If most of the traffic was not from advertising platforms, you can expect at least 10-fold compression of this column. When using a quick compression algorithm, data decompression is possible at a speed of at least several gigabytes of uncompressed data per second. In other words, this query can be processed at a speed of approximately several billion rows per second on a single server. This speed is actually achieved in practice.
</p>

<pre class='terminal show-example'>
milovidov@████████.yandex.ru:~$ clickhouse-client
ClickHouse client version 0.0.52053.
Connecting to localhost:9000.
Connected to ClickHouse server version 0.0.52053.

:) SELECT CounterID, count() FROM hits GROUP BY CounterID ORDER BY count() DESC LIMIT 20

SELECT
    CounterID,
    count()
FROM hits
GROUP BY CounterID
ORDER BY count() DESC
LIMIT 20

┌─CounterID─┬──count()─┐
│    114208 │ 56057344 │
│    115080 │ 51619590 │
│      3228 │ 44658301 │
│     38230 │ 42045932 │
│    145263 │ 42042158 │
│     91244 │ 38297270 │
│    154139 │ 26647572 │
│    150748 │ 24112755 │
│    242232 │ 21302571 │
│    338158 │ 13507087 │
│     62180 │ 12229491 │
│     82264 │ 12187441 │
│    232261 │ 12148031 │
│    146272 │ 11438516 │
│    168777 │ 11403636 │
│   4120072 │ 11227824 │
│  10938808 │ 10519739 │
│     74088 │  9047015 │
│    115079 │  8837972 │
│    337234 │  8205961 │
└───────────┴──────────┘

20 rows in set. Elapsed: 0.153 sec. Processed 1.00 billion rows, 4.00 GB (6.53 billion rows/s., 26.10 GB/s.)

:)
</pre>

<p>2. For CPU.
Since executing a query requires processing a large number of rows, it helps to dispatch all operations for entire vectors instead of for separate rows, or to implement the query engine so that there is almost no dispatching cost. If you don&#39;t do this, with any half-decent disk subsystem, the query interpreter inevitably stalls the CPU.
It makes sense to both store data in columns and process it, when possible, by columns.
</p>
<p>There are two ways to do this:
1. A vector engine. All operations are written for vectors, instead of for separate values. This means you don&#39;t need to call operations very often, and dispatching costs are negligible. Operation code contains an optimized internal cycle.
2. Code generation. The code generated for the query has all the indirect calls in it.
</p>
<p>This is not done in &quot;normal&quot; databases, because it doesn&#39;t make sense when running simple queries. However, there are exceptions. For example, MemSQL uses code generation to reduce latency when processing SQL queries. (For comparison, analytical DBMSs require optimization of throughput, not latency.)
</p>
<p>Note that for CPU efficiency, the query language must be declarative (SQL or MDX), or at least a vector (J, K). The query should only contain implicit loops, allowing for optimization.
</p>

<h2>Distinctive features of ClickHouse</h2>

<p>1. True column-oriented DBMS.
2. Data compression.
3. Disk storage of data.
4. Parallel processing on multiple cores.
5. Distributed processing on multiple servers.
6. SQL support.
7. Vector engine.
8. Real-time data updates.
9. Indexes.
10. Suitable for online queries.
11. Support for approximated calculations.
12. Support for nested data structures. Support for arrays as data types.
13. Support for restrictions on query complexity, along with quotas.
14. Data replication and support for data integrity on replicas.
</p>

<p>Let&#39;s look at some of these features in detail.</p>

<h3 class='not-for-contents'>1. True column-oriented DBMS.</h3>

<p>In a true column-oriented DBMS, there isn&#39;t any &quot;garbage&quot; stored with the values. For example, constant-length values must be supported, to avoid storing their length &quot;number&quot; next to the values. As an example, a billion UInt8-type values should actually consume around 1 GB uncompressed, or this will strongly affect the CPU use. It is very important to store data compactly (without any &quot;garbage&quot;) even when uncompressed, since the speed of decompression (CPU usage) depends mainly on the volume of uncompressed data.</p>

<p>This is worth noting because there are systems that can store values of separate columns separately, but that can&#39;t effectively process analytical queries due to their optimization for other scenarios. Example are HBase, BigTable, Cassandra, and HyperTable. In these systems, you will get throughput around a hundred thousand rows per second, but not hundreds of millions of rows per second.</p>

<p>Also note that ClickHouse is a DBMS, not a single database. ClickHouse allows creating tables and databases in runtime, loading data, and running queries without reconfiguring and restarting the server.</p>

<h3 class='not-for-contents'>2. Data compression.</h3>

<p>Some column-oriented DBMSs (InfiniDB CE and MonetDB) do not use data compression. However, data compression really improves performance.</p>

<h3 class='not-for-contents'>3. Disk storage of data.</h3>

<p>Many column-oriented DBMSs (SAP HANA, Metamarkets Druid, and Google PowerDrill) can only work in RAM. But even on thousands of servers, the RAM is too small for storing all the pageviews and sessions in Yandex.Metrica.</p>

<h3 class='not-for-contents'>4. Parallel processing on multiple cores.</h3>

<p>Large queries are parallelized in a natural way.</p>

<h3 class='not-for-contents'>5. Distributed processing on multiple servers.</h3>

<p>Almost none of the columnar DBMSs listed above have support for distributed processing.
In ClickHouse, data can reside on different shards. Each shard can be a group of replicas that are used for fault tolerance. The query is processed on all the shards in parallel. This is transparent for the user.</p>

<h3 class='not-for-contents'>6. SQL support.</h3>

<p>If you are familiar with standard SQL, we can&#39;t really talk about SQL support.
NULLs are not supported. All the functions have different names. However, this is a declarative query language based on SQL that can&#39;t be differentiated from SQL in many instances.
JOINs are supported. Subqueries are supported in FROM, IN, and JOIN clauses.</p>

<h3 class='not-for-contents'>7. Vector engine.</h3>

<p>Data is not only stored by columns, but is processed by vectors - parts of columns. This allows us to achieve high CPU performance.</p>

<h3 class='not-for-contents'>8. Real-time data updates.</h3>

<p>ClickHouse supports primary key tables. In order to quickly perform queries on the range of the primary key, the data is sorted incrementally using the merge tree. Due to this, data can continually be added to the table. There is no locking when adding data.</p>

<h3 class='not-for-contents'>9. Indexes.</h3>

<p>Having a primary key allows, for example, extracting data for specific clients (Metrica counters) for a specific time range, with low latency less than several dozen milliseconds.</p>

<h3 class='not-for-contents'>10. Suitable for online queries.</h3>

<p>This lets us use the system as the back-end for a web interface. Low latency means queries can be processed without delay, while the Yandex.Metrica interface page is loading (in online mode).</p>

<h3 class='not-for-contents'>11. Support for approximated calculations.</h3>

<p>1. The system contains aggregate functions for approximated calculation of the number of various values, medians, and quantiles.</p>
<p>2. Supports running a query based on a part (sample) of data and getting an approximated result. In this case, proportionally less data is retrieved from the disk.</p>
<p>3. Supports running an aggregation for a limited number of random keys, instead of for all keys. Under certain conditions for key distribution in the data, this provides a reasonably accurate result while using fewer resources.</p>

<h3 class='not-for-contents'>14. Data replication and support for data integrity on replicas.</h3>

<p>Uses asynchronous multimaster replication. After being written to any available replica, data is distributed to all the remaining replicas. The system maintains identical data on different replicas. Data is restored automatically after a failure, or using a &quot;button&quot; for complex cases.</p>
<p>For more information, see the section &quot;Data replication&quot;.</p>

<h2>ClickHouse features that can be considered disadvantages</h2>

<p>1. No transactions.</p>

<p>2. For aggregation, query results must fit in the RAM on a single server. However, the volume of source data for a query may be indefinitely large.</p>

<p>3. Lack of full-fledged UPDATE/DELETE implementation.</p>

<h2>The Yandex.Metrica task</h2>

<p>We need to get custom reports based on hits and sessions, with custom segments set by the user. Data for the reports is updated in real-time. Queries must be run immediately (in online mode). We must be able to build reports for any time period. Complex aggregates must be calculated, such as the number of unique visitors.
At this time (April 2014), Yandex.Metrica receives approximately 12 billion events (pageviews and mouse clicks) daily. All these events must be stored in order to build custom reports. A single query may require scanning hundreds of millions of rows over a few seconds, or millions of rows in no more than a few hundred milliseconds.</p>

<h3>Aggregated and non-aggregated data</h3>

<p>There is a popular opinion that in order to effectively calculate statistics, you must aggregate data, since this reduces the volume of data.</p>

<p>But data aggregation is a very limited solution, for the following reasons:
- You must have a pre-defined list of reports the user will need. The user can&#39;t make custom reports.
- When aggregating a large quantity of keys, the volume of data is not reduced, and aggregation is useless.
- For a large number of reports, there are too many aggregation variations (combinatorial explosion).
- When aggregating keys with high cardinality (such as URLs), the volume of data is not reduced by much (less than twofold). For this reason, the volume of data with aggregation might grow instead of shrink.
- Users will not view all the reports we calculate for them. A large portion of calculations are useless.
- The logical integrity of data may be violated for various aggregations.</p>

<p>If we do not aggregate anything and work with non-aggregated data, this might actually reduce the volume of calculations.</p>

<p>However, with aggregation, a significant part of the work is taken offline and completed relatively calmly. In contrast, online calculations require calculating as fast as possible, since the user is waiting for the result.</p>

<p>Yandex.Metrica has a specialized system for aggregating data called Metrage, which is used for the majority of reports. Starting in 2009, Yandex.Metrica also used a specialized OLAP database for non-aggregated data called OLAPServer, which was previously used for the report builder. OLAPServer worked well for non-aggregated data, but it had many restrictions that did not allow it to be used for all reports as desired. These included the lack of support for data types (only numbers), and the inability to incrementally update data in real-time (it could only be done by rewriting data daily). OLAPServer is not a DBMS, but a specialized DB.</p>

<p>To remove the limitations of OLAPServer and solve the problem of working with non-aggregated data for all reports, we developed the ClickHouse DBMS.</p>

<h2>Usage in Yandex.Metrica and other Yandex services</h2>

<p>ClickHouse is used for multiple purposes in Yandex.Metrica. Its main task is to build reports in online mode using non-aggregated data. It uses a cluster of 374 servers, which store over 8 trillion rows (more than a quadrillion values) in the database. The volume of compressed data, without counting duplication and replication, is about 800 TB. The volume of uncompressed data (in TSV format) would be approximately 7 PB.</p>

<p>ClickHouse is also used for:
- Storing WebVisor data.
- Processing intermediate data.
- Building global reports with Analytics.
- Running queries for debugging the Metrica engine.
- Analyzing logs from the API and the user interface.
</p>

<p>ClickHouse has at least a dozen installations in other Yandex services: in search verticals, Market, Direct, business analytics, mobile development, AdFox, personal services, and others.</p>


<h2>Possible counterparts</h2>

<p>There are no analogs to ClickHouse available.
At this time (May 2016), there aren&#39;t any available open-source and free systems that have all the features listed above. However, these features are absolutely necessary for Yandex.Metrica.</p>


<h2>Performance</h2>

570
<p>According to internal testing results, ClickHouse shows the best performance for comparable operating scenarios among systems of its class that were available for testing. This includes the highest throughput for long queries, and the lowest latency on short queries. Testing results are shown <a href='benchmark.html'>on this page</a>.
571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643
</p>

<h3>Throughput for a single large query</h3>

<p>Throughput can be measured in rows per second or in megabytes per second. If the data is placed in the page cache, a query that is not too complex is processed on modern hardware at a speed of approximately 2-10 GB/s of uncompressed data on a single server (for the simplest cases, the speed may reach 30 GB/s). If data is not placed in the page cache, the speed depends on the disk subsystem and the data compression rate. For example, if the disk subsystem allows reading data at 400 MB/s, and the data compression rate is 3, the speed will be around 1.2 GB/s. To get the speed in rows per second, divide the speed in bytes per second by the total size of the columns used in the query. For example, if 10 bytes of columns are extracted, the speed will be around 100-200 million rows per second.</p>

<p>The processing speed increases almost linearly for distributed processing, but only if the number of rows resulting from aggregation or sorting is not too large.</p>

<h3>Latency when processing short queries.</h3>

<p>If a query uses a primary key and does not select too many rows to process (hundreds of thousands), and does not use too many columns, we can expect less than 50 milliseconds of latency (single digits of milliseconds in the best case) if data is placed in the page cache. Otherwise, latency is calculated from the number of seeks. If you use rotating drives, for a system that is not overloaded, the latency is calculated by this formula: seek time (10 ms) * number of columns queried * number of data parts.</p>

<h3>Throughput when processing a large quantity of short queries.</h3>

<p>Under the same conditions, ClickHouse can handle several hundred queries per second on a single server (up to several thousand in the best case). Since this scenario is not typical for analytical DBMSs, we recommend expecting a maximum of 100 queries per second.</p>

<h3>Performance on data insertion.</h3>

<p>We recommend inserting data in packets of at least 1000 rows, or no more than a single request per second. When inserting to a MergeTree table from a tab-separated dump, the insertion speed will be from 50 to 200 MB/s. If the inserted rows are around 1 Kb in size, the speed will be from 50,000 to 200,000 rows per second. If the rows are small, the performance will be higher in rows per second (on Yandex Banner System data -> 500,000 rows per second, on Graphite data -> 1,000,000 rows per second). To improve performance, you can make multiple INSERT queries in parallel, and performance will increase linearly.</p>

</div>

<div class='island'>
<h1>Getting started</h1>
</div>

<div class='island'>

<h2>System requirements</h2>

<p>This is not a cross-platform system. It requires Linux Ubuntu Precise (12.04) or newer, with x86_64 architecture.
We recommend using Ubuntu Trusty or Ubuntu Precise.
The terminal must use UTF-8 encoding (the default in Ubuntu).</p>


<h2>Installation</h2>

<p>For testing and development, the system can be installed on a single server or on a desktop computer.</p>


<h3>Installing from packages</h3>

<p>In <span class='inline-example'>/etc/apt/sources.list</span> (or in a separate <span class='inline-example'>/etc/apt/sources.list.d/metrika.list</span> file), add the repository:</p>

<p>For internal usage in Yandex, on Ubuntu Trusty (14.04):</p>

<pre class='text-example'>
deb http://dist.yandex.ru/metrika-trusty/ stable/amd64/
</pre>

<p>For internal usage in Yandex, on Ubuntu Precise (12.04):</p>

<pre class='text-example'>
deb http://dist.yandex.ru/metrika/ stable/amd64/
</pre>

<p>Repositories for external users will be documented soon.</p>

<p>Then run:</p>

<pre class='text-example'>
sudo apt-get update
sudo apt-get install clickhouse-client clickhouse-server-common
</pre>

<p>You can also download and install packages manually from here: <a href='https://dist.yandex.ru/metrika/stable/amd64/'>https://dist.yandex.ru/metrika/stable/amd64/</a>.</p>

<p>ClickHouse contains access restriction settings. They are located in the &#39;users.xml&#39; file (next to &#39;config.xml&#39;).
By default, access is allowed from everywhere for the default user without a password. See &#39;user/default/networks&#39;. For more information, see the section &quot;Configuration files&quot;.</p>


<h3>Installing from sources</h3>

A
Alexey Milovidov 已提交
644
<p>Build following the instructions in <a href='https://███████████.yandex-team.ru/raw/Metrika/ClickHouse/master/doc/build.txt'>build.txt</a></p>
645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972

<p>You can compile packages and install them. You can also use programs without installing packages.</p>

<p>Client: src/dbms/src/Client/
Server: src/dbms/src/Server/</p>

<p>For the server, create a catalog with data, such as:</p>

<pre class='text-example'>
/opt/clickhouse/data/default/
/opt/clickhouse/metadata/default/
</pre>

<p>(Configured in the server config.)
Run &#39;chown&#39; for the desired user.</p>

<p>Note the path to logs in the server config (src/dbms/src/Server/config.xml).</p>


<h3>Launch</h3>

<p>To start the server (as a daemon), run:</p>

<pre class='terminal'>
sudo service clickhouse-server start
</pre>

<p>View the logs in the catalog</p>

<pre class='text-example'>
/var/log/clickhouse-server/
</pre>

<p>If the server doesn&#39;t start, check the configurations in the file</p>

<pre class='text-example'>
/etc/clickhouse-server/config.xml
</pre>

<p>You can also launch the server from the console:</p>

<pre class='terminal'>
clickhouse-server --config-file=/etc/clickhouse-server/config.xml
</pre>

<p>In this case, the log will be printed to the console, which is convenient during development. If the configuration file is in the current directory, you don&#39;t need to specify the &#39;--config-file&#39; parameter. By default, it uses &#39;./config.xml&#39;.</p>

<p>You can use the command-line client to connect to the server:</p>

<pre class='terminal'>
clickhouse-client
</pre>

<p>The default parameters indicate connecting with localhost:9000 on behalf of the user &#39;default&#39; without a password.
The client can be used for connecting to a remote server. For example:</p>

<pre class='terminal'>
clickhouse-client --host=example.com
</pre>

<p>For more information, see the section &quot;Command-line client&quot;.</p>

<p>Checking the system:</p>

<pre class='terminal'>
milovidov@milovidov-Latitude-E6320:~/work/metrica/src/dbms/src/Client$ ./clickhouse-client
ClickHouse client version 0.0.18749.
Connecting to localhost:9000.
Connected to ClickHouse server version 0.0.18749.

:) SELECT 1

<i class='c15'>SELECT</i> 1

┌─<i class='c15'>1</i>─┐
│ 1 │
└───┘

1 rows in set. Elapsed: 0.003 sec.

:)
</pre>

<p>Congratulations, it works!</p>

<h2>Test data</h2>

<p>You can use Yandex.Metrica test data to explore the system&#39;s capabilities. You can find instructions for using the test data <a href='https://███████████.yandex-team.ru/Metrika/ClickHouse_private/tree/master/tests'>here</a>.

The test data is made up of a sample of 1/5000th of the Yandex.Metrica data for a week, which is uniformly random by user IDs. Do not expose the test data to possible distribution outside the company.

The volume of the data (less than 2 GB compressed) is appropriate for downloading to a desktop computer or development server.
</p>

<h2>If you have questions</h2>

<p>If you are Yandex employee, use internal ClickHouse maillist.
You can subscribe to this list to get announcements, information on new developments, and questions that other users have.
</p>


</div>
<div class='island'>
<h1>Interfaces</h1>
</div>

<div class='island'>

<p>To explore the system&#39;s capabilities, download data to tables, or make manual queries, use the clickhouse-client program.</p>


<h2>HTTP interface</h2>


<p>The HTTP interface lets you use ClickHouse on any platform from any programming language. We use it for working from Java and Perl, as well as shell scripts. In other departments, the HTTP interface is used from Perl, Python, and Go. The HTTP interface is more limited than the native interface, but it has better compatibility.</p>

<p>By default, clickhouse-server listens for HTTP on port 8123 (this can be changed in the config).
If you make a GET / request without parameters, it returns the string &quot;Ok&quot; (with a line break at the end). You can use this in health-check scripts.</p>

<pre class='terminal'>
$ curl &#39;http://localhost:8123/&#39;
Ok.
</pre>

<p>Send the request as a URL &#39;query&#39; parameter, or as a POST. Or send the beginning of the request in the &#39;query&#39; parameter, and the rest in the POST (we&#39;ll explain later why this is necessary).
If successful, you receive the 200 response code and the result in the response body.
If an error occurs, you receive the 500 response code and an error description text in the response body.</p>

<p>When using the GET method, &#39;readonly&#39; is set. In other words, for queries that modify data, you can only use the POST method. You can send the query itself either in the POST body, or in the URL parameter.</p>

<p>Examples:</p>

<pre class='terminal'>
$ curl &#39;http://localhost:8123/?query=SELECT%201&#39;
1

$ wget -O- -q &#39;http://localhost:8123/?query=SELECT 1&#39;
1

$ GET &#39;http://localhost:8123/?query=SELECT 1&#39;
1

$ echo -ne &#39;GET /?query=SELECT%201 HTTP/1.0\r\n\r\n&#39; | nc localhost 8123
HTTP/1.0 200 OK
Connection: Close
Date: Fri, 16 Nov 2012 19:21:50 GMT

1
</pre>

<p>As you can see, curl is not very convenient because spaces have to be URL-escaped. Although wget escapes everything on its own, we don&#39;t recommend it because it doesn&#39;t work well over HTTP 1.1 when using keep-alive and Transfer-Encoding: chunked.</p>

<pre class='terminal'>
$ echo &#39;SELECT 1&#39; | curl &#39;http://localhost:8123/&#39; --data-binary @-
1

$ echo &#39;SELECT 1&#39; | curl &#39;http://localhost:8123/?query=&#39; --data-binary @-
1

$ echo &#39;1&#39; | curl &#39;http://localhost:8123/?query=SELECT&#39; --data-binary @-
1
</pre>

<p>If part of the query is sent in the parameter, and part in the POST, a line break is inserted between these two data parts.
Example (this won&#39;t work):</p>

<pre class='terminal'>
$ echo &#39;ECT 1&#39; | curl &#39;http://localhost:8123/?query=SEL&#39; --data-binary @-
Code: 59, e.displayText() = DB::Exception: Syntax error: failed at position 0: SEL
ECT 1
, expected One of: SHOW TABLES, SHOW DATABASES, SELECT, INSERT, CREATE, ATTACH, RENAME, DROP, DETACH, USE, SET, OPTIMIZE., e.what() = DB::Exception
</pre>

<p>By default, data is returned in TabSeparated format (for more information, see the &quot;Formats&quot; section).
You use the FORMAT clause of the query to request any other format.</p>

<pre class='terminal'>
$ echo &#39;SELECT 1 FORMAT Pretty&#39; | curl &#39;http://localhost:8123/?&#39; --data-binary @-
┏━━━┓
┃ 1 ┃
┡━━━┩
│ 1 │
└───┘
</pre>

<p>The POST method of transmitting data is necessary for INSERT queries. In this case, you can write the beginning of the query in the URL parameter, and use POST to pass the data to insert. The data to insert could be, for example, a tab-separated dump from MySQL. In this way, the INSERT query replaces LOAD DATA LOCAL INFILE from MySQL.</p>

<p>Examples:</p>

<p>Creating a table:</p>

<pre class='terminal'>
echo &#39;CREATE TABLE t (a UInt8) ENGINE = Memory&#39; | POST &#39;http://localhost:8123/&#39;
</pre>

<p>Using the familiar INSERT query for data insertion:</p>

<pre class='terminal'>
echo &#39;INSERT INTO t VALUES (1),(2),(3)&#39; | POST &#39;http://localhost:8123/&#39;
</pre>

<p>Data can be sent separately from the query:</p>

<pre class='terminal'>
echo &#39;(4),(5),(6)&#39; | POST &#39;http://localhost:8123/?query=INSERT INTO t VALUES&#39;
</pre>

<p>You can specify any data format. The &#39;Values&#39; format is the same as what is used when writing INSERT INTO t VALUES:</p>

<pre class='terminal'>
echo &#39;(7),(8),(9)&#39; | POST &#39;http://localhost:8123/?query=INSERT INTO t FORMAT Values&#39;
</pre>

<p>To insert data from a tab-separated dump, specify the corresponding format:</p>

<pre class='terminal'>
echo -ne &#39;10\n11\n12\n&#39; | POST &#39;http://localhost:8123/?query=INSERT INTO t FORMAT TabSeparated&#39;
</pre>

<p>Reading the table contents. Data is output in random order due to parallel query processing:</p>

<pre class='terminal'>
$ GET &#39;http://localhost:8123/?query=SELECT a FROM t&#39;
7
8
9
10
11
12
1
2
3
4
5
6
</pre>

<p>Deleting the table.</p>

<pre class='terminal'>
POST &#39;http://localhost:8123/?query=DROP TABLE t&#39;
</pre>

<p>For successful requests that don&#39;t return a data table, an empty response body is returned.</p>

<p>You can use compression when transmitting data. The compressed data has a non-standard format, and you will need to use a special compressor program to work with it (<span class='inline-example'>sudo apt-get install compressor-metrika-yandex</span>).</p>

<p>If you specified &#39;compress=1&#39; in the URL, the server will compress the data it sends you.
If you specified &#39;decompress=1&#39; in the URL, the server will decompress the same data that you pass in the POST method.</p>

<p>You can use this to reduce network traffic when transmitting a large amount of data, or for creating dumps that are immediately compressed.</p>

<p>You can use the &#39;database&#39; URL parameter to specify the default database.</p>

<pre class='terminal'>
$ echo &#39;SELECT number FROM numbers LIMIT 10&#39; | curl &#39;http://localhost:8123/?database=system&#39; --data-binary @-
0
1
2
3
4
5
6
7
8
9
</pre>

<p>By default, the database that is registered in the server settings is used as the default database. By default, this is the database called &#39;default&#39;. Alternatively, you can always specify the database using a dot before the table name.</p>

<p>The username and password can be indicated in one of two ways:
1. Using HTTP Basic Authentication. Example:
<pre class='terminal'>
echo &#39;SELECT 1&#39; | curl &#39;http://user:password@localhost:8123/&#39; -d @-
</pre>
2. In the &#39;user&#39; and &#39;password&#39; URL parameters. Example:
<pre class='terminal'>
echo &#39;SELECT 1&#39; | curl &#39;http://localhost:8123/?user=user&amp;password=password&#39; -d @-
</pre>
If the user name is not indicated, the username &#39;default&#39; is used. If the password is not indicated, an empty password is used.
</p>

<p>You can also use the URL parameters to specify any settings for processing a single query, or entire profiles of settings. Example: </p>

<pre>http://localhost:8123/?profile=web&amp;max_rows_to_read=1000000000&amp;query=SELECT+1</pre>

<p>For more information, see the section &quot;Settings&quot;.</p>

<pre class='terminal'>
$ echo &#39;SELECT number FROM system.numbers LIMIT 10&#39; | curl &#39;http://localhost:8123/?&#39; --data-binary @-
0
1
2
3
4
5
6
7
8
9
</pre>

<p>For information about other parameters, see the section &quot;SET&quot;.</p>

<p>In contrast to the native interface, the HTTP interface does not support the concept of sessions or session settings, does not allow aborting a query (to be exact, it allows this in only a few cases),  and does not show the progress of query processing. Parsing and data formatting are performed on the server side, and using the network might be ineffective.</p>

<p>The optional &#39;query_id&#39; parameter can be passed as the query ID (any string). For more information, see the section &quot;Settings, replace_running_query&quot;.</p>

<p>The optional &#39;quota_key&#39; parameter can be passed as the quota key (any string). For more information, see the section &quot;Quotas&quot;.</p>

<p>The HTTP interface allows passing external data (external temporary tables) for querying. For more information, see the section &quot;External data for query processing&quot;.</p>


<h2>Native interface (TCP)</h2>

The native interface is used in the &quot;clickhouse-client&quot; command-line client for interaction between servers with distributed query processing, and also in C++ programs. We will only cover the command-line client.

<h2>Command-line client</h2>

<pre class='terminal'>
$ clickhouse-client
ClickHouse client version 0.0.26176.
Connecting to localhost:9000.
Connected to ClickHouse server version 0.0.26176.

:) SELECT 1
</pre>

A
Alexey Milovidov 已提交
973
<p>The &quot;clickhouse-client&quot; program accepts the following parameters, which are all optional:</p>
974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990

<p>--host, -h - server name, by default - &#39;localhost&#39;.
You can use either the name or the IPv4 or IPv6 address.</p>

<p>--port - The port to connect to, by default - &#39;9000&#39;.
Note that the HTTP interface and the native interface use different ports.</p>

<p>--user, -u - The username, by default - &#39;default&#39;.</p>

<p>--password - The password, by default - empty string.</p>

<p>--query, -q - Query to process when using non-interactive mode.</p>

<p>--database, -d - Select the current default database, by default - the current DB from the server settings (by default, the &#39;default&#39; DB).</p>

<p>--multiline, -m - If specified, allow multiline queries (do not send request on Enter).</p>

A
Alexey Milovidov 已提交
991
<p>--multiquery, -n - If specified, allow processing multiple queries separated by semicolons.
992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030
Only works in non-interactive mode.</p>

<p>--format, -f - Use the specified default format to output the result.</p>

<p>--vertical, -E - If specified, use the Vertical format by default to output the result. This is the same as &#39;--format=Vertical&#39;. In this format, each value is printed on a separate line, which is helpful when displaying wide tables.</p>

<p>--time, -t - If specified, print the query execution time to &#39;stderr&#39; in non-interactive mode.</p>

<p>--stacktrace - If specified, also prints the stack trace if an exception occurs.</p>

<p>--config-file - Name of the configuration file that has additional settings or changed defaults for the settings listed above.
By default, files are searched for in this order:
./clickhouse-client.xml
~/./clickhouse-client/config.xml
/etc/clickhouse-client/config.xml
Settings are only taken from the first file found.</p>

<p>You can also specify any settings that will be used for processing queries. For example, <span class='inline-example'>clickhouse-client --max_threads=1</span>. For more information, see the section &quot;Settings&quot;.</p>

<p>The client can be used in interactive and non-interactive (batch) mode.
To use batch mode, specify the &#39;query&#39; parameter, or send data to &#39;stdin&#39; (it verifies that &#39;stdin&#39; is not a terminal), or both.
Similar to the HTTP interface, when using the &#39;query&#39; parameter and sending data to &#39;stdin&#39;, the request is a concatenation of the &#39;query&#39; parameter, a line break, and the data in &#39;stdin&#39;. This is convenient for large INSERT queries.
In batch mode, the default data format is TabSeparated. You can set the format in the FORMAT clause of the query.</p>

<p>By default, you can only process a single query in batch mode. To make multiple queries from a &quot;script,&quot; use the &#39;multiquery&#39; parameter. This works for all queries except INSERT. Query results are output consecutively without additional separators.
Similarly, to process a large number of queries, you can run &#39;clickhouse-client&#39; for each query. Note that it may take tens of milliseconds to launch the &#39;clickhouse-client&#39; program.</p>

<p>In interactive mode, you get a command line where you can enter queries.

If &#39;multiline&#39; is not specified (the default):
To run a query, press Enter. The semicolon is not necessary at the end of the query. To enter a multiline query, enter a backslash <span class='inline-example'>\</span> before the line break - after you press Enter, you will be asked to enter the next line of the query.

If &#39;multiline&#39; is specified:
To run a query, end it with a semicolon and press Enter. If the semicolon was omitted at the end of the entered line, you will be asked to enter the next line of the query.

Only a single query is run, so everything after the semicolon is ignored.</p>

<p>You can specify <span class='inline-example'>\G</span> instead of or after the semicolon. This indicates using Vertical format. In this format, each value is printed on a separate line, which is convenient for wide tables. This unusual feature was added for compatibility with the MySQL CLI.</p>

A
Alexey Milovidov 已提交
1031
<p>The command line is based on &#39;readline&#39; (and &#39;history&#39;) (or &#39;libedit&#39;, or even nothing, depending on build). In other words, it uses the familiar keyboard shortcuts and keeps a history. The history is written to /.clickhouse-client-history.</p>
1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335

<p>By default, the format used is PrettyCompact. You can change the format in the FORMAT clause of the query, or by specifying &#39;\G&#39; at the end of the query, using the &#39;--format&#39; or &#39;--vertical&#39; argument in the command line, or using the client configuration file.</p>

<p>To exit the client, press Ctrl+D (or Ctrl+C), or enter one of the following :
&quot;exit&quot;, &quot;quit&quot;, &quot;logout&quot;, &quot;учше&quot;, &quot;йгше&quot;, &quot;дщпщге&quot;, &quot;exit;&quot;, &quot;quit;&quot;, &quot;logout;&quot;, &quot;учшеж&quot;, &quot;йгшеж&quot;, &quot;дщпщгеж&quot;, &quot;q&quot;, &quot;й&quot;, &quot;\q&quot;, &quot;\Q&quot;, &quot;:q&quot;, &quot;&quot;, &quot;&quot;, &quot;Жй&quot;</p>

<p>When processing a query, the client shows:
1. Progress, which is updated no more than 10 times per second (by default). For quick queries, the progress might not have time to be displayed.
2. The formatted query after parsing, for debugging.
3. The result in the specified format.
4. The number of lines in the result, the time passed, and the average speed of query processing.</p>

<p>To cancel a lengthy query, press Ctrl+C. However, you will still need to wait a little for the server to abort the request. It is not possible to cancel a query at certain stages. If you don&#39;t wait and press Ctrl+C a second time, the client will exit.</p>

<p>The command-line client allows passing external data (external temporary tables) for querying. For more information, see the section &quot;External data for request processing&quot;.</p>


</div>
<div class='island'>
<h1>Query language</h1>
</div>

<div class='island'>

<h2>Syntax</h2>

<p>There are two types of parsers in the system: a full SQL parser (a recursive descend parser), and a data format parser (a fast stream parser). In all cases except the INSERT query, only the full SQL parser is used.
The INSERT query uses both parsers:</p>

<pre class='text-example'>INSERT INTO t VALUES (1, &#39;Hello, world&#39;), (2, &#39;abc&#39;), (3, &#39;def&#39;)</pre>

<p>The <span class='inline-example'>INSERT INTO t VALUES</span> fragment is parsed by the full parser, and the data <span class='inline-example'>(1, &#39;Hello, world&#39;), (2, &#39;abc&#39;), (3, &#39;def&#39;)</span> is parsed by the fast stream parser.
Data can have any format. When a query is received, the server calculates no more than &#39;max_query_size&#39; bytes of the request in RAM (by default, 1 MB), and the rest is stream parsed. This means the system doesn&#39;t have problems with large INSERT queries, like MySQL does.</p>

<p>When using the Values format in an INSERT query, it may seem that data is parsed the same as expressions in a SELECT query, but this is not true. The Values format is much more limited.</p>

<p>Next we will cover the full parser. For more information about format parsers, see the section &quot;Formats&quot;.</p>

<h3>Spaces</h3>

<p>There may be any number of space symbols between syntactical constructions (including the beginning and end of a query). Space symbols include the space, tab, line break, CR, and form feed.</p>

<h3>Comments</h3>

<p>SQL-style and C-style comments are supported.
SQL-style comments: from <span class='inline-example'>--</span> to the end of the line. The space after <span class='inline-example'>--</span> can be omitted.
C-style comments: from <span class='inline-example'>/*</span> to <span class='inline-example'>*/</span>. These comments can be multiline. Spaces are not required here, either.</p>

<h3>Keywords</h3>

<p>Keywords (such as SELECT) are not case-sensitive. Everything else (column names, functions, and so on), in contrast to standard SQL, is case-sensitive. Keywords are not reserved (they are just parsed as keywords in the corresponding context).</p>

<h3>Identifiers</h3>

<p>Identifiers (column names, functions, and data types) can be quoted or non-quoted.
Non-quoted identifiers start with a Latin letter or underscore, and continue with a Latin letter, underscore, or number. In other words, they must match the regex <span class='inline-example'>^[a-zA-Z_][0-9a-zA-Z_]*$</span>. Examples: <span class='inline-example'>x</span>, <span class='inline-example'>_1</span>, <span class='inline-example'>X_y__Z123_</span>.
Quoted identifiers are placed in reversed quotation marks <span class='inline-example'>`id`</span> (the same as in MySQL), and can indicate any set of bytes (non-empty). In addition, symbols (for example, the reverse quotation mark) inside this type of identifier can be backslash-escaped. Escaping rules are the same as for string literals (see below).
We recommend using identifiers that do not need to be quoted.</p>

<h3>Literals</h3>

<p>There are numeric literals, string literals, and compound literals.</p>

<h4>Numeric literals</h4>

<p>A numeric literal tries to be parsed:
- first as a 64-bit signed number, using the &#39;strtoull&#39; function.
- if unsuccessful, as a 64-bit unsigned number, using the &#39;strtoll&#39; function.
- if unsuccessful, as a floating-point number using the &#39;strtod&#39; function.
- otherwise, an error is returned.</p>

<p>The corresponding value will have the smallest type that the value fits in.
For example, 1 is parsed as UInt8, but 256 is parsed as UInt16. For more information, see &quot;Data types&quot;.</p>

<p>Examples: <span class='inline-example'>1</span>, <span class='inline-example'>18446744073709551615</span>, <span class='inline-example'>0xDEADBEEF</span>, <span class='inline-example'>01</span>, <span class='inline-example'>0.1</span>, <span class='inline-example'>1e100</span>, <span class='inline-example'>-1e-100</span>, <span class='inline-example'>inf</span>, <span class='inline-example'>nan</span>.</p>

<h4>String literals</h4>

<p>Only string literals in single quotes are supported. The enclosed characters can be backslash-escaped. The following escape sequences have special meanings: <span class='inline-example'>\b</span>, <span class='inline-example'>\f</span>, <span class='inline-example'>\r</span>, <span class='inline-example'>\n</span>, <span class='inline-example'>\t</span>, <span class='inline-example'>\0</span>. In all other cases, escape sequences like <span class='inline-example'>\<i>x</i></span>, where <i>x</i> is any character, are transformed to <i>x</i>. This means that the sequences <span class='inline-example'>\&#39;</span> and <span class='inline-example'>\\</span> can be used. The value will have the String type.</p>

<h4>Compound literals</h4>

<p>Constructions are supported for arrays: <span class='inline-example'>[1, 2, 3]</span> and tuples: <span class='inline-example'>(1, &#39;Hello, world!&#39;, 2)</span>.
Actually, these are not literals, but expressions with the array creation operator and the tuple creation operator, respectively. For more information, see the section &quot;Operators2&quot;.
An array must consist of at least one item, and a tuple must have at least two items.
Tuples have a special purpose for use in the IN clause of a SELECT query. Tuples can be obtained as the result of a query, but they can&#39;t be saved to a database (with the exception of Memory-type tables).</p>

<h3>Functions</h3>

<p>Functions are written like an identifier with a list of arguments (possibly empty) in brackets. In contrast to standard SQL, the brackets are required, even for an empty arguments list. Example: <span class='inline-example'>now()</span>.
There are regular and aggregate functions (see the section &quot;Aggregate functions&quot;). Some aggregate functions can contain two lists of arguments in brackets. Example: <span class='inline-example'>quantile(0.9)(x)</span>. These aggregate functions are called &quot;parametric&quot; functions, and the arguments in the first list are called &quot;parameters&quot;. The syntax of aggregate functions without parameters is the same as for regular functions.</p>

<h3>Operators</h3>

<p>Operators are converted to their corresponding functions during query parsing, taking their priority and associativity into account.
For example, the expression <span class='inline-example'>1 + 2 * 3 + 4</span> is transformed to <span class='inline-example'>plus(plus(1, multiply(2, 3)), 4)</span>.
For more information, see the section &quot;Operators2&quot; below.</p>

<h3>Data types and database table engines</h3>

<p>Data types and table engines in the CREATE query are written the same way as identifiers or functions. In other words, they may or may not contain an arguments list in brackets. For more information, see the sections &quot;Data types,&quot; &quot;Table engines,&quot; and &quot;CREATE&quot;.</p>

<h3>Synonyms</h3>

<p>In the SELECT query, expressions can specify synonyms using the AS keyword. Any expression is placed to the left of AS. The identifier name for the synonym is placed to the right of AS. As opposed to standard SQL, synonyms are not only declared on the top level of expressions:</p>

<pre class='text-example'>SELECT (1 AS n) + 2, n</pre>

<p>In contrast to standard SQL, synonyms can be used in all parts of a query, not just SELECT.</p>

<h3>Asterisk</h3>

<p>In a SELECT query, an asterisk can replace the expression. For more information, see the section &quot;SELECT&quot;.</p>

<h3>Expressions</h3>

<p>An expression is a function, identifier, literal, application of an operator, expression in brackets, subquery, or asterisk. It can also contain a synonym.
A list of expressions is one or more expressions separated by commas.
Functions and operators, in turn, can have expressions as arguments.</p>


<h2>Queries</h2>


<h3>CREATE DATABASE</h3>

<pre class='text-example'>CREATE DATABASE [IF NOT EXISTS] db_name</pre>

<p>- Creates the &#39;db_name&#39; database. A database is just a directory for tables.
If &quot;IF NOT EXISTS&quot; is included, the query won&#39;t return an error if the database already exists.</p>

<h3>CREATE TABLE</h3>

<p>The CREATE TABLE query can have several forms.</p>

<pre class='text-example'>CREATE [TEMPORARY] TABLE [IF NOT EXISTS] [db.]name
(
    name1 [type1] [DEFAULT|MATERIALIZED|ALIAS expr1],
    name2 [type2] [DEFAULT|MATERIALIZED|ALIAS expr2],
    ...
) ENGINE = engine</pre>

<p>Creates a table named &#39;name&#39; in the &#39;db&#39; database or the current database if &#39;db&#39; is not set, with the structure specified in brackets and the &#39;engine&#39; engine. The structure of the table is a list of column descriptions. If indexes are supported by the engine, they are indicated as parameters for the table engine.</p>

<p>A column description is <span class='inline-example'>name type</span> in the simplest case. For example: <span class='inline-example'>RegionID UInt32</span>.
Expressions can also be defined for default values (see below).</p>

<pre class='text-example'>CREATE [TEMPORARY] TABLE [IF NOT EXISTS] [db.]name AS [db2.]name2 [ENGINE = engine]</pre>

<p>Creates a table with the same structure as another table. You can specify a different engine for the table. If the engine is not specified, the same engine will be used as for the &#39;db2.name2&#39; table.</p>

<pre class='text-example'>CREATE [TEMPORARY] TABLE [IF NOT EXISTS] [db.]name ENGINE = engine AS SELECT ...</pre>

<p>Creates a table with a structure like the result of the SELECT query, with the &#39;engine&#39; engine, and fills it with data from SELECT.</p>

<p>In all cases, if IF NOT EXISTS is specified, the query won&#39;t return an error if the table already exists. In this case, the query won&#39;t do anything.</p>

<h4>Default values</h4>

<p>The column description can specify an expression for a default value, in one of the following ways:
<span class='inline-example'>DEFAULT expr</span>, <span class='inline-example'>MATERIALIZED expr</span>, <span class='inline-example'>ALIAS expr</span>.
Example: <span class='inline-example'>URLDomain String DEFAULT domain(URL)</span>.</p>

<p>If an expression for the default value is not defined, the default values will be set to zeros for numbers, empty strings for strings, empty arrays for arrays, and 0000-00-00 for dates or 0000-00-00 00:00:00 for dates with time. NULLs are not supported.</p>

<p>If the default expression is defined, the column type is optional. If there isn&#39;t an explicitly defined type, the default expression type is used. Example: <span class='inline-example'>EventDate DEFAULT toDate(EventTime)</span> - the &#39;Date&#39; type will be used for the &#39;EventDate&#39; column.</p>

<p>If the data type and default expression are defined explicitly, this expression will be cast to the specified type using type casting functions. Example: <span class='inline-example'>Hits UInt32 DEFAULT 0</span> means the same thing as <span class='inline-example'>Hits UInt32 DEFAULT toUInt32(0)</span>.</p>

<p>Default expressions may be defined as an arbitrary expression from table constants and columns. When creating and changing the table structure, it checks that expressions don&#39;t contain loops. For INSERT, it checks that expressions are resolvable - that all columns they can be calculated from have been passed.</p>

<pre class='text-example'>DEFAULT expr</pre>

<p>Normal default value. If the INSERT query doesn&#39;t specify the corresponding column, it will be filled in by computing the corresponding expression.</p>

<pre class='text-example'>MATERIALIZED expr</pre>

<p>Materialized expression. Such a column can&#39;t be specified for INSERT, because it is always calculated.
For an INSERT without a list of columns, these columns are not considered.
In addition, this column is not substituted when using an asterisk in a SELECT query. This is to preserve the invariant that the dump obtained using SELECT * can be inserted back into the table using INSERT without specifying the list of columns.</p>

<pre class='text-example'>ALIAS expr</pre>

<p>Synonym. Such a column isn&#39;t stored in the table at all.
Its values can&#39;t be inserted in a table, and it is not substituted when using an asterisk in a SELECT query.
It can be used in SELECTs if the alias is expanded during query parsing.</p>

<p>When using the ALTER query to add new columns, old data for these columns is not written. Instead, when reading old data that does not have values for the new columns, expressions are computed on the fly by default. However, if running the expressions requires different columns that are not indicated in the query, these columns will additionally be read, but only for the blocks of data that need it.</p>

<p>If you add a new column to a table but later change its default expression, the values used for old data will change (for data where values were not stored on the disk). Note that when running background merges, data for columns that are missing in one of the merging parts is written to the merged part.</p>

<p>It is not possible to set default values for elements in nested data structures.</p>


<h4>Temporary tables</h4>

<p>In all cases, if TEMPORARY is specified, a temporary table will be created. Temporary tables have the following characteristics:
- Temporary tables disappear when the session ends, including if the connection is lost.
- A temporary table is created with the Memory engine. The other table engines are not supported.
- The DB can&#39;t be specified for a temporary table. It is created outside of databases.
- If a temporary table has the same name as another one and a query specifies the table name without specifying the DB, the temporary table will be used.
- For distributed query processing, temporary tables used in a query are passed to remote servers.</p>

<p>In most cases, temporary tables are not created manually, but when using external data for a query, or for distributed (GLOBAL) IN. For more information, see the appropriate sections.</p>

<h3>CREATE VIEW</h3>

<pre class='text-example'>CREATE [MATERIALIZED] VIEW [IF NOT EXISTS] [db.]name [ENGINE = engine] [POPULATE] AS SELECT ...</pre>

<p>Creates a view. There are two types of views: normal and MATERIALIZED.</p>

<p>Normal views don&#39;t store any data, but just perform a read from another table. In other words, a normal view is nothing more than a saved query. When reading from a view, this saved query is used as a subquery in the FROM clause.

As an example, assume you&#39;ve created a view:
<pre class='text-example'>CREATE VIEW view AS SELECT ...</pre>
and written a query:
<pre class='text-example'>SELECT a, b, c FROM view</pre>
This query is fully equivalent to using the subquery:
<pre class='text-example'>SELECT a, b, c FROM (SELECT ...)</pre>
</p>

<p>Materialized views store data transformed by the corresponding SELECT query.

When creating a materialized view, you can specify ENGINE - the table engine for storing data. By default, it uses the same engine as for the table that the SELECT query is made from.

A materialized view is arranged as follows: when inserting data to the table specified in SELECT, part of the inserted data is converted by this SELECT query, and the result is inserted in the view.

If you specify POPULATE, the existing table data is inserted in the view when creating it, as if making a CREATE TABLE ... AS SELECT ... query. Otherwise, the query contains only the data inserted in the table after creating the view. We don&#39;t recommend using POPULATE, since data inserted in the table during the view creation will not be inserted in it.

The SELECT query can contain DISTINCT, GROUP BY, ORDER BY, LIMIT ... Note that the corresponding conversions are performed independently on each block of inserted data. For example, if GROUP BY is set, data is aggregated during insertion, but only within a single packet of inserted data. The data won&#39;t be further aggregated. The exception is when using an ENGINE that independently performs data aggregation, such as SummingMergeTree.

The execution of ALTER queries on materialized views has not been fully developed, so they might be inconvenient.</p>

<p>Views look the same as normal tables. For example, they are listed in the result of the SHOW TABLES query.</p>

<p>There isn&#39;t a separate query for deleting views. To delete a view, use DROP TABLE.</p>

<h3>ATTACH</h3>

<p>The query is exactly the same as CREATE, except
- The word ATTACH is used instead of CREATE.
- The query doesn&#39;t create data on the disk, but assumes that data is already in the appropriate places, and just adds information about the table to the server.
After executing an ATTACH query, the server will know about the existence of the table.</p>

<p>This query is used when starting the server. The server stores table metadata as files with ATTACH queries, which it simply runs at launch (with the exception of system tables, which are explicitly created on the server).</p>


<h3>DROP</h3>

<p>This query has two types: DROP DATABASE and DROP TABLE.</p>

<pre class='text-example'>DROP DATABASE [IF EXISTS] db</pre>

<p>Deletes all tables inside the &#39;db&#39; database, then deletes the &#39;db&#39; database itself.
If IF EXISTS is specified, it doesn&#39;t return an error if the database doesn&#39;t exist.</p>

<pre class='text-example'>DROP TABLE [IF EXISTS] [db.]name</pre>

<p>Deletes the table.
If IF EXISTS is specified, it doesn&#39;t return an error if the table doesn&#39;t exist or the database doesn&#39;t exist.</p>


<h3>DETACH</h3>

<pre class='text-example'>DETACH TABLE [IF EXISTS] [db.]name</pre>

<p>Deletes information about the table from the server. The server stops knowing about the table&#39;s existence. This does not delete the table&#39;s data or metadata. On the next server launch, the server will read the metadata and find out about the table again. Similarly, a &quot;detached&quot; table can be re-attached using the ATTACH query (with the exception of system tables, which do not have metadata stored for them).</p>

<p>There is no DETACH DATABASE query.</p>


<h3>RENAME</h3>

<pre class='text-example'>RENAME TABLE [db11.]name11 TO [db12.]name12, [db21.]name21 TO [db22.]name22, ...</pre>

<p>Renames one or more tables. All tables are renamed under global locking. Renaming tables is a light operation. If you indicated another database after TO, the table will be moved to this database. However, the directories with databases must reside in the same file system (otherwise, an error is returned).</p>


<h3>ALTER</h3>

<p>The ALTER query is only supported for *MergeTree type tables, as well as for Merge and Distributed types. The query has several variations.</p>

<h4>Column manipulations</h4>

<pre class='text-example'>ALTER TABLE [db].name ADD|DROP|MODIFY COLUMN ...</pre>

<p>Lets you change the table structure. In the query, specify a list of one or more comma-separated actions. Each action is an operation on a column.</p>

<p>The following actions are supported:</p>

<pre class='text-example'>ADD COLUMN name [type] [default_expr] [AFTER name_after]</pre>

<p>Adds a new column to the table with the specified name, type, and default expression (see the section &quot;Default expressions&quot;). If you specify &#39;AFTER name_after&#39; (the name of another column), the column is added after the specified one in the list of table columns. Otherwise, the column is added to the end of the table. Note that there is no way to add a column to the beginning of a table. For a chain of actions, &#39;name_after&#39; can be the name of a column that is added in one of the previous actions.</p>

<p>Adding a column just changes the table structure, without performing any actions with data. The data doesn&#39;t appear on the disk after ALTER. If the data is missing for a column when reading from the table, it is filled in with default values (by performing the default expression if there is one, or using zeros or empty strings). The column appears on the disk after merging data parts (see MergeTree).</p>

<p>This approach allows us to complete the ALTER query instantly, without increasing the volume of old data.</p>

<pre class='text-example'>DROP COLUMN name</pre>

<p>Deletes the column with the name &#39;name&#39;.</p>

<p>Deletes data from the file system. Since this deletes entire files, the query is completed almost instantly.</p>

<pre class='text-example'>MODIFY COLUMN name [type] [default_expr]</pre>

<p>Changes the &#39;name&#39; column&#39;s type to &#39;type&#39; and/or the default expression to &#39;default_expr&#39;. When changing the type, values are converted as if the &#39;to<i>Type</i>&#39; function were applied to them.</p>

<p>If only the default expression is changed, the query doesn&#39;t do anything complex, and is completed almost instantly.</p>

<p>Changing the column type is the only complex action - it changes the contents of files with data. For large tables, this may take a long time.</p>

<p>There are several stages of execution:
- Preparing temporary (new) files with modified data.
- Renaming old files.
- Renaming the temporary (new) files to the old names.
- Deleting the old files.</p>

<p>Only the first stage takes time. If there is a failure at this stage, the data is not changed.
If there is a failure during one of the successive stages, data can be restored manually. The exception is if the old files were deleted from the file system but the data for the new files did not get written to the disk and was lost.</p>

<p>There is no support for changing the column type in arrays and nested data structures.</p>

<p>The ALTER query lets you create and delete separate elements (columns) in nested data structures, but not whole nested data structures. To add a nested data structure, you can add columns with a name like &#39;name.nested_name&#39; and the type &#39;Array(<i>T</i>)&#39;. A nested data structure is equivalent to multiple array columns with a name that has the same prefix before the dot.</p>

<p>There is no support for deleting or changing the type for columns in the primary key or the sampling key (columns that are in the ENGINE expression).</p>

<p>If the ALTER query is not sufficient for making the table changes you need, you can create a new table, copy the data to it using the INSERT SELECT query, then switch the tables using the RENAME query and delete the old table.</p>

<p>The ALTER query blocks all reads and writes for the table. In other words, if a long SELECT is running at the time of the ALTER query, the ALTER query will wait for the SELECT to complete. At the same time, all new queries to the same table will wait while this ALTER is running.</p>

<p>For tables that don&#39;t store data themselves (Merge and Distributed), ALTER just changes the table structure, and does not change the structure of subordinate tables. For example, when running ALTER for a Distributed table, you will also need to run ALTER for the tables on all remote servers.</p>

<p>The ALTER query for changing columns is replicated. The instructions are saved in ZooKeeper, then each replica applies them. All ALTER queries are run in the same order. The query waits for the appropriate actions to be completed on the other replicas. However, a query to change columns in a replicated table can be interrupted, and all actions will be performed asynchronously.</p>


<h4>Manipulations with partitions and parts</h4>

<p>Only works for tables in the MergeTree family. The following operations are available:

<span class='inline-example'>DETACH PARTITION</span> - Move a partition to the &#39;detached&#39; directory and forget it.
<span class='inline-example'>DROP PARTITION</span> - Delete a partition.
<span class='inline-example'>ATTACH PART|PARTITION</span> - Add a new part or partition from the &#39;detached&#39; directory to the table.
<span class='inline-example'>FREEZE PARTITION</span> - Create a backup of a partition.
<span class='inline-example'>FETCH PARTITION</span> - Download a partition from another server.

Each type of query is covered separately below.</p>

<p>A partition in a table is data for a single calendar month. This is determined by the values of the date key specified in the table engine parameters. Each month&#39;s data is stored separately in order to simplify manipulations with this data.</p>

<p>A &quot;part&quot; in the table is part of the data from a single partition, sorted by the primary key.</p>

<p>You can use the system.parts table to view the set of table parts and partitions:</p>

<pre class='text-example'>SELECT * FROM system.parts WHERE active</pre>

<p>active - Only count active parts. Inactive parts are, for example, source parts remaining after merging to a larger part - these parts are deleted approximately 10 minutes after merging.</p>

<p>Another way to view a set of parts and partitions is to go into the directory with table data.
The directory with data is
/opt/clickhouse/data/<i>database</i>/<i>table</i>/,
where /opt/clickhouse/ is the path to ClickHouse data, &#39;database&#39; is the database name, and &#39;table&#39; is the table name. Example:</p>

<pre class='text-example'>
$ ls -l /opt/clickhouse/data/test/visits/
total 48
drwxrwxrwx 2 metrika metrika 20480 may   13 02:58 20140317_20140323_2_2_0
drwxrwxrwx 2 metrika metrika 20480 may   13 02:58 20140317_20140323_4_4_0
drwxrwxrwx 2 metrika metrika  4096 may   13 02:55 detached
-rw-rw-rw- 1 metrika metrika     2 may   13 02:58 increment.txt
</pre>

<p>Here 20140317_20140323_2_2_0 and 20140317_20140323_4_4_0 are directories of parts.

Let&#39;s look at the name of the first part: 20140317_20140323_2_2_0.
20140317 - minimum date of part data
20140323 - maximum date of part data
2 - minimum number of the data block
2 - maximum number of the data block
0 - part level - depth of the merge tree that formed it

Each part corresponds to a single partition and contains data for a single month.
201403 - The partition name. A partition is a set of parts for a single month.</p>

<p>On an operating server, you can&#39;t manually change the set of parts or their data on the file system, since the server won&#39;t know about it. For non-replicated tables, you can do this when the server is stopped, but we don&#39;t recommended it. For replicated tables, the set of parts can&#39;t be changed in any case.</p>

<p>The &#39;detached&#39; directory contains parts that are not used by the server - detached from the table using the ALTER ... DETACH query. Parts that are damaged are also moved to this directory, instead of deleting them. You can add, delete, or modify the data in the &#39;detached&#39; directory at any time - the server won&#39;t know about this until you make the ALTER TABLE ... ATTACH query.</p>

<p>For replicated tables, there is also an &#39;unreplicated&#39; directory. This directory can hold the portion of table data that does not participate in replication. This data is present only if the table was converted from a non-replicated one (see the section &quot;Conversion from MergeTree to ReplicatedMergeTree&quot;).</p>


<pre class='text-example'>ALTER TABLE [db.]table DETACH [UNREPLICATED] PARTITION &#39;name&#39;</pre>

<p>Move all data for partitions named &#39;name&#39; to the &#39;detached&#39; directory and forget about them.
The partition name is specified in YYYYMM format. It can be indicated in single quotes or without them.</p>

<p>After the query is executed, you can do whatever you want with the data in the &#39;detached&#39; directory — delete it from the file system, or just leave it.</p>

<p>If UNREPLICATED is specified (this only works for replicatable tables), the query is run for the unreplicated part of a replicatable table.</p>

<p>The query is replicated - data will be moved to the &#39;detached&#39; directory and forgotten on all replicas. The query can only be sent to a leader replica. To find out if a replica is a leader, perform SELECT to the &#39;system.replicas&#39; system table. Alternatively, it is easier to make a query on all replicas, and all except one will throw an exception.</p>


<pre class='text-example'>ALTER TABLE [db.]table DROP [UNREPLICATED] PARTITION &#39;name&#39;</pre>

<p>Similar to the DETACH operation. Deletes data from the table. Data parts will be tagged as inactive and will be completely deleted in approximately 10 minutes. The query is replicated - data will be deleted on all replicas.</p>


<pre class='text-example'>ALTER TABLE [db.]table ATTACH [UNREPLICATED] PARTITION|PART &#39;name&#39;</pre>

<p>Adds data to the table from the &#39;detached&#39; directory. Or, if UNREPLICATED is specified, data is moved from an &#39;unreplicated&#39; part to replicated data.</p>

<p>It is possible to add data for an entire partition or a separate part. For a part, specify the full name of the part in single quotes.</p>

<p>The query is replicated. Each replica checks whether there is data in the &#39;detached&#39; directory. If there is data, it checks the integrity, verifies that it matches the data on the server that initiated the query, and then adds it if everything is correct. If not, it downloads data from the query requestor replica, or from another replica where the data has already been added.</p>

<p>So you can put data in the &#39;detached&#39; directory on one replica, and use the ALTER ... ATTACH query to add it to the table on all replicas.</p>


<pre class='text-example'>ALTER TABLE [db.]table FREEZE PARTITION &#39;name&#39;</pre>

<p>Creates a local backup of one or multiple partitions. The name can be the full name of the partition (for example, 201403), or its prefix (for example, 2014) - then the backup will be created for all the corresponding partitions.</p>

<p>The query does the following: for a data snapshot at the time of execution, it creates hardlinks to table data in the directory /opt/clickhouse/shadow/N/...
/opt/clickhouse/ is the working ClickHouse directory from the config.
N is the incremental number of the backup.
The same structure of directories is created inside the backup as inside /opt/clickhouse/.
It also performs &#39;chmod&#39; for all files, forbidding writes to them.</p>

<p>The backup is created almost instantly (but first it waits for current queries to the corresponding table to finish running). At first, the backup doesn&#39;t take any space on the disk. As the system works, the backup can take disk space, as data is modified. If the backup is made for old enough data, it won&#39;t take space on the disk.</p>

<p>After creating the backup, data from /opt/clickhouse/shadow/ can be copied to the remote server and then deleted on the local server. The entire backup process is performed without stopping the server.</p>

<p>The ALTER ... FREEZE PARTITION query is not replicated. A local backup is only created on the local server.</p>

<p>As an alternative, you can manually copy data from the /opt/clickhouse/data/database/table directory. But if you do this while the server is running, race conditions are possible when copying directories with files being added or changed, and the backup may be inconsistent. You can do this if the server isn&#39;t running - then the resulting data will be the same as after the ALTER TABLE t FREEZE PARTITION query.</p>

<p>ALTER TABLE ... FREEZE PARTITION only copies data, not table metadata. To make a backup of table metadata, copy the file  /opt/clickhouse/metadata/database/table.sql</p>

<p>To restore from a backup:
- Use the CREATE query to create the table if it doesn&#39;t exist. The query can be taken from an .sql file (replace ATTACH in it with CREATE).
- Copy data from the data/database/table/ directory inside the backup to the /opt/clickhouse/data/database/table/detached/ directory.
- Run ALTER TABLE ... ATTACH PARTITION YYYYMM queries where YYYYMM is the month, for every month.</p>

<p>In this way, data from the backup will be added to the table.
Restoring from a backup doesn&#39;t require stopping the server.</p>

<p><b>Backups and replication</b></p>

<p>Replication provides protection from device failures. If all data disappeared on one of your replicas, follow the instructions in the &quot;Restoration after failure&quot; section to restore it.</p>

<p>For protection from device failures, you must use replication. For more information about replication, see the section &quot;Data replication&quot;.</p>

<p>Backups protect against human error (accidentally deleting data, deleting the wrong data or in the wrong cluster, or corrupting data). For high-volume databases, it can be difficult to copy backups to remote servers. In such cases, to protect from human error, you can keep a backup on the same server (it will reside in /opt/clickhouse/shadow/).</p>


<pre class='text-example'>ALTER TABLE [db.]table FETCH PARTITION &#39;name&#39; FROM &#39;path-in-zookeeper&#39;</pre>

<p>This query only works for replicatable tables.</p>

<p>It downloads the specified partition from the shard that has its ZooKeeper path specified in the FROM clause, then puts it in the &#39;detached&#39; directory for the specified table.</p>

<p>Although the query is called ALTER TABLE, it does not change the table structure, and does not immediately change the data available in the table.</p>

<p>Data is placed in the &#39;detached&#39; directory. You can use the ALTER TABLE ... ATTACH query to attach the data.</p>

<p>The path to ZooKeeper is specified in the FROM clause. For example, <span class='inline-example'>/clickhouse/tables/01-01/visits</span>.
Before downloading, the system checks that the partition exists and the table structure matches. The most appropriate replica is selected automatically from the healthy replicas.</p>

<p>The ALTER ... FETCH PARTITION query is not replicated. The partition will be downloaded to the &#39;detached&#39; directory only on the local server. Note that if after this you use the ALTER TABLE ... ATTACH query to add data to the table, the data will be added on all replicas (on one of the replicas it will be added from the &#39;detached&#39; directory, and on the rest it will be loaded from neighboring replicas).</p>


<h4>Synchronicity of ALTER queries</h4>

<p>For non-replicatable tables, all ALTER queries are performed synchronously. For replicatable tables, the query just adds instructions for the appropriate actions to ZooKeeper, and the actions themselves are performed as soon as possible. However, the query can wait for these actions to be completed on all the replicas.</p>

<p>For ALTER ... ATTACH|DETACH|DROP queries, you can use the &#39;replication_alter_partitions_sync&#39; setting to set up waiting.
Possible values: 0 - do not wait, 1 - wait for own completion (default), 2 - wait for all.</p>



<h3>SHOW DATABASES</h3>

<pre class='text-example'>SHOW DATABASES [FORMAT format]</pre>

<p>Prints a list of all databases.
This query is identical to the query SELECT name FROM system.databases [FORMAT format]
See the section &quot;Formats&quot;.</p>


<h3>SHOW TABLES</h3>

<pre class='text-example'>SHOW TABLES [FROM db] [LIKE &#39;pattern&#39;] [FORMAT format]</pre>

<p>Outputs a list of
- tables from the current database, or from the &#39;db&#39; database if &quot;FROM db&quot; is specified.
- all tables, or tables whose name matches the pattern, if &quot;LIKE &#39;pattern&#39;&quot; is specified.</p>

<p>The query is identical to the query  SELECT name FROM system.tables
WHERE database = &#39;db&#39; [AND name LIKE &#39;pattern&#39;] [FORMAT format]
See the section &quot;LIKE operator&quot;.</p>


<h3>SHOW PROCESSLIST</h3>

<pre class='text-example'>SHOW PROCESSLIST [FORMAT format]</pre>

<p>Outputs a list of queries currently being processed, other than SHOW PROCESSLIST queries.</p>

<p>Prints a table containing the columns:</p>

<p><b>user</b> is the user who made the query. Keep in mind that for distributed processing, queries are sent to remote servers under the &#39;default&#39; user. SHOW PROCESSLIST shows the username for a specific query, not for a query that this query initiated.</p>

<p><b>address</b> is the name of the host that the query was sent from. For distributed processing, on remote servers, this is the name of the query requestor host. To track where a distributed query was originally made from, look at SHOW PROCESSLIST on the query requestor server.</p>

<p><b>elapsed</b> - The execution time, in seconds. Queries are output in order of decreasing execution time.</p>

<p><b>rows_read</b>, <b>bytes_read</b> - How many rows and bytes of uncompressed data were read when processing the query. For distributed processing, data is totaled from all the remote servers. This is the data used for restrictions and quotas.</p>

<p><b>memory_usage</b> - Current RAM usage in bytes. See the setting &#39;max_memory_usage&#39;.</p>

<p><b>query</b> - The query itself. In INSERT queries, the data for insertion is not output.</p>

<p><b>query_id</b> - The query identifier. Non-empty only if it was explicitly defined by the user. For distributed processing, the query ID is not passed to remote servers.</p>

<p>This query is exactly the same as: SELECT * FROM system.processes [FORMAT format].</p>

<p>Tip (execute in the console): </p>
<pre class='text-example'>watch -n1 &quot;clickhouse-client --query=&#39;SHOW PROCESSLIST&#39;&quot;</pre>


<h3>SHOW CREATE TABLE</h3>

<pre class='text-example'>SHOW CREATE TABLE [db.]table [FORMAT format]</pre>

<p>Returns a single String-type &#39;statement&#39; column, which contains a single value - the CREATE query used for creating the specified table.</p>


<h3>DESCRIBE TABLE</h3>

<pre class='text-example'>DESC|DESCRIBE TABLE [db.]table [FORMAT format]</pre>

<p>Returns two String-type columns: &#39;name&#39; and &#39;type&#39;, which indicate the names and types of columns in the specified table.</p>

<p>Nested data structures are output in &quot;expanded&quot; format. Each column is shown separately, with the name after a dot.</p>


<h3>EXISTS</h3>

<pre class='text-example'>EXISTS TABLE [db.]name [FORMAT format]</pre>

<p>Returns a single UInt8-type column, which contains the single value 0 if the table or database doesn&#39;t exist, or 1 if the table exists in the specified database.</p>


<h3>USE</h3>

<pre class='text-example'>USE db</pre>

<p>Lets you set the current database for the session.
The current database is used for searching for tables if the database is not explicitly defined in the query with a dot before the table name.
This query can&#39;t be made when using the HTTP protocol, since there is no concept of a session.</p>


<h3>SET</h3>

<pre class='text-example'>SET [GLOBAL] param = value</pre>

<p>Lets you set the &#39;param&#39; setting to &#39;value&#39;. You can also make all the settings from the specified settings profile in a single query. To do this, specify &#39;profile&#39; as the setting name. For more information, see the section &quot;Settings&quot;. The setting is made for the session, or for the server (globally) if GLOBAL is specified.
When making a global setting, the setting is not applied to sessions already running, including the current session. It will only be used for new sessions.</p>

<p>Settings made using SET GLOBAL have a lower priority compared with settings made in the config file in the user profile. In other words, user settings can&#39;t be overridden by SET GLOBAL.</p>

<p>When the server is restarted, global settings made using SET GLOBAL are lost.
To make settings that persist after a server restart, you can only use the server&#39;s config file. (This can&#39;t be done using a SET query.)</p>


<h3>OPTIMIZE</h3>

<pre class='text-example'>OPTIMIZE TABLE [db.]name</pre>

<p>Asks the table engine to do something for optimization.
Supported only by *MergeTree engines, in which this query initializes a non-scheduled merge of data parts.</p>

<p>For replicated tables, the OPTIMIZE query is only applied to non-replicated data (this data exists only after converting non-replicated tables to replicated ones). If there isn&#39;t any, the query doesn&#39;t do anything.</p>


<h3>INSERT</h3>

<p>This query has several variations.</p>

<pre class='text-example'>INSERT INTO [db.]table [(c1, c2, c3)] VALUES (v11, v12, v13), (v21, v22, v23), ...</pre>

<p>Inserts rows with the listed values in the &#39;table&#39; table. This query is exactly the same as:</p>

<pre class='text-example'>INSERT INTO [db.]table [(c1, c2, c3)] FORMAT Values (v11, v12, v13), (v21, v22, v23), ...</pre>

<pre class='text-example'>INSERT INTO [db.]table [(c1, c2, c3)] FORMAT format ...</pre>

<p>Inserts data in any specified format.
The data itself comes after &#39;format&#39;, after all space symbols up to the first line break if there is one and including it, or after all space symbols if there isn&#39;t a line break. We recommend writing data starting from the next line (this is important if the data starts with space characters).</p>

<p>Example:</p>

<pre class='text-example'>INSERT INTO t FORMAT TabSeparated
11  Hello, world!
22  Qwerty
</pre>

<p>For more information about data formats, see the section &quot;Formats&quot;. The &quot;Interfaces&quot; section describes how to insert data separately from the query when using the command-line client or the HTTP interface.</p>

<p>The query may optionally specify a list of columns for insertion. In this case, the default values are written to the other columns.
Default values are calculated from DEFAULT expressions specified in table definitions, or, if the DEFAULT is not explicitly defined, zeros and empty strings are used. If the &#39;strict_insert_default&#39; setting is set to 1, all the columns that do not have explicit DEFAULTS must be specified in the query.</p>

<pre class='text-example'>INSERT INTO [db.]table [(c1, c2, c3)] SELECT ...</pre>

<p>Inserts the result of the SELECT query into a table.
The names and data types of the SELECT result must exactly match the table structure that data is inserted into, or the specified list of columns.
To change column names, use synonyms (AS) in the SELECT query.
To change data types, use type conversion functions (see the section &quot;Functions&quot;).</p>

<p>None of the data formats allows using expressions as values.
In other words, you can&#39;t write INSERT INTO t VALUES (now(), 1 + 1, DEFAULT).</p>

<p>There is no support for other data part modification queries:
UPDATE, DELETE, REPLACE, MERGE, UPSERT, INSERT UPDATE.
However, you can delete old data using ALTER TABLE ... DROP PARTITION.</p>


<h3>SELECT</h3>

<p>His Highness, the SELECT query.</p>

<pre class='text-example'>SELECT [DISTINCT] expr_list
    [FROM [db.]table | (subquery) | table_function] [FINAL]
    [SAMPLE sample_coeff]
    [ARRAY JOIN ...]
    [GLOBAL] ANY|ALL INNER|LEFT JOIN (subquery)|table USING columns_list
    [PREWHERE expr]
    [WHERE expr]
    [GROUP BY expr_list] [WITH TOTALS]
    [HAVING expr]
    [ORDER BY expr_list]
    [LIMIT [n, ]m]
    [UNION ALL ...]
    [FORMAT format]</pre>

<p>All the clauses are optional, except for the required list of expressions immediately after SELECT.
The clauses below are described in almost the same order as in the query execution conveyor.</p>

<p>If the query omits the DISTINCT, GROUP BY, and ORDER BY clauses and the IN and JOIN subqueries, the query will be completely stream processed, using O(1) amount of RAM.
Otherwise, the query may consume too much RAM, if appropriate restrictions are not defined (max_memory_usage, max_rows_to_group_by, max_rows_to_sort, max_rows_in_distinct, max_bytes_in_distinct, max_rows_in_set, max_bytes_in_set, max_rows_in_join, max_bytes_in_join, max_bytes_before_external_sort). For more information, see the section &quot;Settings&quot;. It is possible to use external sorting (saving temporary tables to a disk). The system does not have external aggregation or merge join.</p>

<h4>FROM clause</h4>

<p>If the FROM clause is omitted, data will be read from the &#39;system.one&#39; table.
The &#39;system.one&#39; table contains exactly one row (this table fulfills the same purpose as the DUAL table found in other DBMSs).</p>

<p>The FROM clause specifies the table to read data from, or a subquery, or a table function; ARRAY JOIN and the regular JOIN may also be included (see below).</p>

<p>Instead of a table, the SELECT subquery may be specified in brackets. In this case, the subquery processing pipeline will be built into the processing pipeline of an external query.
In contrast to standard SQL, a synonym does not need to be specified after a subquery. For compatibility, it is possible to write &#39;AS name&#39; after a subquery, but the specified name isn&#39;t used anywhere.</p>

<p>A table function may be specified instead of a table. For more information, see the section &quot;Table functions&quot;.</p>

<p>To execute a query, all the columns listed in the query are extracted from the appropriate table. Any columns not needed for the external query are thrown out of the subqueries.
If a query does not list any columns (for example, SELECT count() FROM t), some column is extracted from the table anyway (the smallest one is preferred), in order to calculate the number of rows.</p>

<p>The FINAL modifier can be used only for a SELECT from a CollapsingMergeTree table. When you specify FINAL, data is selected fully &quot;collapsed&quot;. Keep in mind that using FINAL leads to a selection that includes columns related to the primary key, in addition to the columns specified in the SELECT. Additionally, the query will be executed in a single stream, and data will be merged during query execution. This means that when using FINAL, the query is processed more slowly. In most cases, you should avoid using FINAL. For more information, see the section &quot;CollapsingMergeTree engine&quot;.</p>

<h4>SAMPLE clause</h4>

<p>The SAMPLE clause allows for approximated query processing.
Approximated query processing is only supported by MergeTree* type tables, and only if the sampling expression was specified during table creation (see the section &quot;MergeTree engine&quot;).

SAMPLE has the format <span class='inline-example'>SAMPLE k</span>, where &#39;k&#39; is a decimal number from 0 to 1, or <span class='inline-example'>SAMPLE n</span>, where &#39;n&#39; is a sufficiently large integer.

In the first case, the query will be executed on &#39;k&#39; percent of data. For example, <span class='inline-example'>SAMPLE 0.1</span> runs the query on 10% of data.
In the second case, the query will be executed on a sample of no more than &#39;n&#39; rows. For example, <span class='inline-example'>SAMPLE 10000000</span> runs the query on a maximum of 10,000,000 rows.

Example:</p>

<pre class='text-example'>SELECT
    Title,
    count() * 10 AS PageViews
FROM hits_distributed
SAMPLE 0.1
WHERE
    CounterID = 34
    AND toDate(EventDate) >= toDate(&#39;2013-01-29&#39;)
    AND toDate(EventDate) &lt;= toDate(&#39;2013-02-04&#39;)
    AND NOT DontCountHits
    AND NOT Refresh
    AND Title != &#39;&#39;
GROUP BY Title
ORDER BY PageViews DESC LIMIT 1000</pre>

<p>In this example, the query is executed on a sample from 0.1 (10%) of data. Values of aggregate functions are not corrected automatically, so to get an approximate result, the value &#39;count()&#39; is manually multiplied by 10.

When using something like <span class='inline-example'>SAMPLE 10000000</span>, there isn&#39;t any information about which relative percent of data was processed or what the aggregate functions should be multiplied by, so this method of writing is not always appropriate to the situation.</p>

<p>A sample with a relative coefficient is &quot;consistent&quot;: if we look at all possible data that could be in the table, a sample (when using a single sampling expression specified during table creation) with the same coefficient always selects the same subset of possible data. In other words, a sample from different tables on different servers at different times is made the same way.</p>

<p>For example, a sample of user IDs takes rows with the same subset of all the possible user IDs from different tables. This allows using the sample in subqueries in the IN clause, as well as for manually correlating results of different queries with samples.</p>

<h4>ARRAY JOIN clause</h4>

<p>Allows executing JOIN with an array or nested data structure. The intent is similar to the &#39;arrayJoin&#39; function, but its functionality is broader.</p>

<p>ARRAY JOIN is essentially INNER JOIN with an array. Example:</p>

<pre class='text-example'>
:) CREATE TABLE arrays_test (s String, arr Array(UInt8)) ENGINE = Memory

CREATE TABLE arrays_test
(
    s String,
    arr Array(UInt8)
) ENGINE = Memory

Ok.

0 rows in set. Elapsed: 0.001 sec.

:) INSERT INTO arrays_test VALUES (&#39;Hello&#39;, [1,2]), (&#39;World&#39;, [3,4,5]), (&#39;Goodbye&#39;, [])

INSERT INTO arrays_test VALUES

Ok.

3 rows in set. Elapsed: 0.001 sec.

:) SELECT * FROM arrays_test

SELECT *
FROM arrays_test

┌─s───────┬─arr─────┐
│ Hello   │ [1,2]   │
│ World   │ [3,4,5] │
│ Goodbye │ []      │
└─────────┴─────────┘

3 rows in set. Elapsed: 0.001 sec.

:) SELECT s, arr FROM arrays_test ARRAY JOIN arr

SELECT s, arr
FROM arrays_test
ARRAY JOIN arr

┌─s─────┬─arr─┐
│ Hello │   1 │
│ Hello │   2 │
│ World │   3 │
│ World │   4 │
│ World │   5 │
└───────┴─────┘

5 rows in set. Elapsed: 0.001 sec.
</pre>

<p>An alias can be specified for an array in the ARRAY JOIN clause. In this case, an array item can be accessed by this alias, but the array itself by the original name. Example:</p>

<pre class='text-example'>
:) SELECT s, arr, a FROM arrays_test ARRAY JOIN arr AS a

SELECT s, arr, a
FROM arrays_test
ARRAY JOIN arr AS a

┌─s─────┬─arr─────┬─a─┐
│ Hello │ [1,2]   │ 1 │
│ Hello │ [1,2]   │ 2 │
│ World │ [3,4,5] │ 3 │
│ World │ [3,4,5] │ 4 │
│ World │ [3,4,5] │ 5 │
└───────┴─────────┴───┘

5 rows in set. Elapsed: 0.001 sec.
</pre>

<p>Multiple arrays of the same size can be comma-separated in the ARRAY JOIN clause. In this case, JOIN is performed with them simultaneously (the direct sum, not the direct product).
Example:</p>

<pre class='text-example'>
:) SELECT s, arr, a, num, mapped FROM arrays_test ARRAY JOIN arr AS a, arrayEnumerate(arr) AS num, arrayMap(x -> x + 1, arr) AS mapped

SELECT s, arr, a, num, mapped
FROM arrays_test
ARRAY JOIN arr AS a, arrayEnumerate(arr) AS num, arrayMap(lambda(tuple(x), plus(x, 1)), arr) AS mapped

┌─s─────┬─arr─────┬─a─┬─num─┬─mapped─┐
│ Hello │ [1,2]   │ 1 │   1 │      2 │
│ Hello │ [1,2]   │ 2 │   2 │      3 │
│ World │ [3,4,5] │ 3 │   1 │      4 │
│ World │ [3,4,5] │ 4 │   2 │      5 │
│ World │ [3,4,5] │ 5 │   3 │      6 │
└───────┴─────────┴───┴─────┴────────┘

5 rows in set. Elapsed: 0.002 sec.

:) SELECT s, arr, a, num, arrayEnumerate(arr) FROM arrays_test ARRAY JOIN arr AS a, arrayEnumerate(arr) AS num

SELECT s, arr, a, num, arrayEnumerate(arr)
FROM arrays_test
ARRAY JOIN arr AS a, arrayEnumerate(arr) AS num

┌─s─────┬─arr─────┬─a─┬─num─┬─arrayEnumerate(arr)─┐
│ Hello │ [1,2]   │ 1 │   1 │ [1,2]               │
│ Hello │ [1,2]   │ 2 │   2 │ [1,2]               │
│ World │ [3,4,5] │ 3 │   1 │ [1,2,3]             │
│ World │ [3,4,5] │ 4 │   2 │ [1,2,3]             │
│ World │ [3,4,5] │ 5 │   3 │ [1,2,3]             │
└───────┴─────────┴───┴─────┴─────────────────────┘

5 rows in set. Elapsed: 0.002 sec.
</pre>

<p>ARRAY JOIN also works with nested data structures. Example:</p>

<pre class='text-example'>
:) CREATE TABLE nested_test (s String, nest Nested(x UInt8, y UInt32)) ENGINE = Memory

CREATE TABLE nested_test
(
    s String,
    nest Nested(
    x UInt8,
    y UInt32)
) ENGINE = Memory

Ok.

0 rows in set. Elapsed: 0.006 sec.

:) INSERT INTO nested_test VALUES (&#39;Hello&#39;, [1,2], [10,20]), (&#39;World&#39;, [3,4,5], [30,40,50]), (&#39;Goodbye&#39;, [], [])

INSERT INTO nested_test VALUES

Ok.

3 rows in set. Elapsed: 0.001 sec.

:) SELECT * FROM nested_test

SELECT *
FROM nested_test

┌─s───────┬─nest.x──┬─nest.y─────┐
│ Hello   │ [1,2]   │ [10,20]    │
│ World   │ [3,4,5] │ [30,40,50] │
│ Goodbye │ []      │ []         │
└─────────┴─────────┴────────────┘

3 rows in set. Elapsed: 0.001 sec.

:) SELECT s, nest.x, nest.y FROM nested_test ARRAY JOIN nest

SELECT s, `nest.x`, `nest.y`
FROM nested_test
ARRAY JOIN nest

┌─s─────┬─nest.x─┬─nest.y─┐
│ Hello │      1 │     10 │
│ Hello │      2 │     20 │
│ World │      3 │     30 │
│ World │      4 │     40 │
│ World │      5 │     50 │
└───────┴────────┴────────┘

5 rows in set. Elapsed: 0.001 sec.
</pre>

<p>When specifying names of nested data structures in ARRAY JOIN, the meaning is the same as ARRAY JOIN with all the array elements that it consists of. Example:</p>

<pre class='text-example'>
:) SELECT s, nest.x, nest.y FROM nested_test ARRAY JOIN nest.x, nest.y

SELECT s, `nest.x`, `nest.y`
FROM nested_test
ARRAY JOIN `nest.x`, `nest.y`

┌─s─────┬─nest.x─┬─nest.y─┐
│ Hello │      1 │     10 │
│ Hello │      2 │     20 │
│ World │      3 │     30 │
│ World │      4 │     40 │
│ World │      5 │     50 │
└───────┴────────┴────────┘

5 rows in set. Elapsed: 0.001 sec.
</pre>

<p>This variation also makes sense:</p>

<pre class='text-example'>
:) SELECT s, nest.x, nest.y FROM nested_test ARRAY JOIN nest.x

SELECT s, `nest.x`, `nest.y`
FROM nested_test
ARRAY JOIN `nest.x`

┌─s─────┬─nest.x─┬─nest.y─────┐
│ Hello │      1 │ [10,20]    │
│ Hello │      2 │ [10,20]    │
│ World │      3 │ [30,40,50] │
│ World │      4 │ [30,40,50] │
│ World │      5 │ [30,40,50] │
└───────┴────────┴────────────┘

5 rows in set. Elapsed: 0.001 sec.
</pre>

<p>An alias may be used for a nested data structure, in order to select either the JOIN result or the source array. Example:</p>

<pre class='text-example'>
:) SELECT s, n.x, n.y, nest.x, nest.y FROM nested_test ARRAY JOIN nest AS n

SELECT s, `n.x`, `n.y`, `nest.x`, `nest.y`
FROM nested_test
ARRAY JOIN nest AS n

┌─s─────┬─n.x─┬─n.y─┬─nest.x──┬─nest.y─────┐
│ Hello │   1 │  10 │ [1,2]   │ [10,20]    │
│ Hello │   2 │  20 │ [1,2]   │ [10,20]    │
│ World │   3 │  30 │ [3,4,5] │ [30,40,50] │
│ World │   4 │  40 │ [3,4,5] │ [30,40,50] │
│ World │   5 │  50 │ [3,4,5] │ [30,40,50] │
└───────┴─────┴─────┴─────────┴────────────┘

5 rows in set. Elapsed: 0.001 sec.
</pre>

<p>Example of using the arrayEnumerate function:</p>

<pre class='text-example'>
:) SELECT s, n.x, n.y, nest.x, nest.y, num FROM nested_test ARRAY JOIN nest AS n, arrayEnumerate(nest.x) AS num

SELECT s, `n.x`, `n.y`, `nest.x`, `nest.y`, num
FROM nested_test
ARRAY JOIN nest AS n, arrayEnumerate(`nest.x`) AS num

┌─s─────┬─n.x─┬─n.y─┬─nest.x──┬─nest.y─────┬─num─┐
│ Hello │   1 │  10 │ [1,2]   │ [10,20]    │   1 │
│ Hello │   2 │  20 │ [1,2]   │ [10,20]    │   2 │
│ World │   3 │  30 │ [3,4,5] │ [30,40,50] │   1 │
│ World │   4 │  40 │ [3,4,5] │ [30,40,50] │   2 │
│ World │   5 │  50 │ [3,4,5] │ [30,40,50] │   3 │
└───────┴─────┴─────┴─────────┴────────────┴─────┘

5 rows in set. Elapsed: 0.002 sec.
</pre>

<p>The query can only specify a single ARRAY JOIN clause.</p>

<p>The corresponding conversion can be performed before the WHERE/PREWHERE clause (if its result is needed in this clause), or after completing WHERE/PREWHERE (to reduce the volume of calculations).</p>

<h4>JOIN clause</h4>

<p>The normal JOIN, which is not related to ARRAY JOIN described above.</p>

<pre class='text-example'>
[GLOBAL] ANY|ALL INNER|LEFT [OUTER] JOIN (subquery)|table USING columns_list
</pre>

<p>Performs joins with data from the subquery. At the beginning of query execution, the subquery specified after JOIN is run, and its result is saved in memory. Then it is read from the &quot;left&quot; table specified in the FROM clause, and while it is being read, for each of the read rows from the &quot;left&quot; table, rows are selected from the subquery results table (the &quot;right&quot; table) that meet the condition for matching the values of the columns specified in USING.</p>

<p>The table name can be specified instead of a subquery. This is equivalent to the &#39;SELECT * FROM table&#39; subquery, except in a special case when the table has the Join engine - an array prepared for joining.</p>

<p>All columns that are not needed for the JOIN are deleted from the subquery.</p>

<p>There are several types of JOINs:</p>

<p>INNER or LEFT - the type:
If INNER is specified, the result will contain only those rows that have a matching row in the right table.
If LEFT is specified, any rows in the left table that don&#39;t have matching rows in the right table will be assigned the default value - zeros or empty rows. LEFT OUTER may be written instead of LEFT; the word OUTER does not affect anything.</p>

<p>ANY or ALL - strictness:
If ANY is specified and there are multiple matching rows in the right table, only the first one will be joined.
If ALL is specified and there are multiple matching rows in the right table, the data will be multiplied by the number of these rows.</p>

<p>Using ALL corresponds to the normal JOIN semantic from standard SQL.
Using ANY is optimal. If the right table has only one matching row, the results of ANY and ALL are the same. You must specify either ANY or ALL (neither of them is selected by default).</p>

<p>GLOBAL - distribution:</p>

<p>When using a normal <span class='inline-example'>JOIN</span>, the query is sent to remote servers. Subqueries are run on each of them in order to make the right table, and the join is performed with this table. In other words, the right table is formed on each server separately.</p>

<p>When using <span class='inline-example'>GLOBAL ... JOIN</span>, first the requestor server runs a subquery to calculate the right table. This temporary table is passed to each remote server, and queries are run on them using the temporary data that was transmitted.</p>

<p>Be careful when using GLOBAL JOINs. For more information, see the section &quot;Distributed subqueries&quot; below.</p>

<p>Any combination of JOINs is possible. For example, <span class='inline-example'>GLOBAL ANY LEFT OUTER JOIN</span>.</p>

<p>When running JOINs, there is no optimization of the order of execution in relation to other stages of the query. The join (a search in the right table) is run before filtering in WHERE and before aggregation. In order to explicitly set the order of execution, we recommend running a JOIN subquery with a subquery.</p>

<p>Example:</p>
<pre class='text-example'>
SELECT
    CounterID,
    hits,
    visits
FROM
(
    SELECT
        CounterID,
        count() AS hits
    FROM test.hits
    GROUP BY CounterID
) ANY LEFT JOIN
(
    SELECT
        CounterID,
        sum(Sign) AS visits
    FROM test.visits
    GROUP BY CounterID
) USING CounterID
ORDER BY hits DESC
LIMIT 10

┌─CounterID─┬───hits─┬─visits─┐
│   1143050 │ 523264 │  13665 │
│    731962 │ 475698 │ 102716 │
│    722545 │ 337212 │ 108187 │
│    722889 │ 252197 │  10547 │
│   2237260 │ 196036 │   9522 │
│  23057320 │ 147211 │   7689 │
│    722818 │  90109 │  17847 │
│     48221 │  85379 │   4652 │
│  19762435 │  77807 │   7026 │
│    722884 │  77492 │  11056 │
└───────────┴────────┴────────┘
</pre>

<p>Subqueries don&#39;t allow you to set names or use them for referencing a column from a specific subquery.
The columns specified in USING must have the same names in both subqueries, and the other columns must be named differently. You can use aliases to change the names of columns in subqueries (the example uses the aliases &#39;hits&#39; and &#39;visits&#39;).</p>

<p>The USING clause specifies one or more columns to join, which establishes the equality of these columns. The list of columns is set without brackets. More complex join conditions are not supported.</p>

<p>The right table (the subquery result) resides in RAM. If there isn&#39;t enough memory, you can&#39;t run a JOIN.</p>

<p>Only one JOIN can be specified in a query (on a single level). To run multiple JOINs, you can put them in subqueries.</p>

<p>Each time a query is run with the same JOIN, the subquery is run again - the result is not cached. To avoid this, use the special &#39;Join&#39; table engine, which is a prepared array for joining that is always in RAM. For more information, see the section &quot;Table engines, Join&quot;.</p>

<p>In some cases, it is more efficient to use IN instead of JOIN. Among the various types of JOINs, the most efficient is ANY LEFT JOIN, then ANY INNER JOIN. The least efficient are ALL LEFT JOIN and ALL INNER JOIN.</p>

<p>If you need a JOIN for joining with dimension tables (these are relatively small tables that contain dimension properties, such as names for advertising campaigns), a JOIN might not be very convenient due to the bulky syntax and the fact that the right table is re-accessed for every query. For such cases, there is an &quot;external dictionaries&quot; feature that you should use instead of JOIN. For more information, see the section &quot;External dictionaries&quot;.</p>


<h4>WHERE clause</h4>

<p>If there is a WHERE clause, it must contain an expression with the UInt8 type. This is usually an expression with comparison and logical operators.
This expression will be used for filtering data before all other transformations.</p>

<p>If indexes are supported by the database table engine, the expression is evaluated on the ability to use indexes.</p>

<h4>PREWHERE clause</h4>

<p>This clause has the same meaning as the WHERE clause. The difference is in which data is read from the table. When using PREWHERE, first only the columns necessary for executing PREWHERE are read. Then the other columns are read that are needed for running the query, but only those blocks where the PREWHERE expression is true.</p>

<p>It makes sense to use PREWHERE if there are filtration conditions that are not suitable for indexes that are used by a minority of the columns in the query, but that provide strong data filtration. This reduces the volume of data to read.</p>

<p>For example, it is useful to write PREWHERE for queries that extract a large number of columns, but that only have filtration for a few columns.</p>

<p>PREWHERE is only supported by *MergeTree tables.</p>

<p>A query may simultaneously specify PREWHERE and WHERE. In this case, PREWHERE precedes WHERE.</p>

<p>Keep in mind that it does not make much sense for PREWHERE to only specify those columns that have an index, because when using an index, only the data blocks that match the index are read.</p>

<p>If the &#39;optimize_move_to_prewhere&#39; setting is set to 1 and PREWHERE is omitted, the system uses heuristics to automatically move parts of expressions from WHERE to PREWHERE.</p>


<h4>GROUP BY clause</h4>

<p>This is one of the most important parts of a column-oriented DBMS.</p>

<p>If there is a GROUP BY clause, it must contain a list of expressions. Each expression will be referred to here as a &quot;key&quot;.
All the expressions in the SELECT, HAVING, and ORDER BY clauses must be calculated from keys or from aggregate functions. In other words, each column selected from the table must be used either in keys or inside aggregate functions.</p>

<p>If a query contains only table columns inside aggregate functions, the GROUP BY clause can be omitted, and aggregation by an empty set of keys is assumed.</p>

<p>Example:</p>

<pre class='text-example'>SELECT
    count(),
    median(FetchTiming > 60 ? 60 : FetchTiming),
    count() - sum(Refresh)
FROM hits</pre>

<p>However, in contrast to standard SQL, if the table doesn&#39;t have any rows (either there aren&#39;t any at all, or there aren&#39;t any after using WHERE to filter), an empty result is returned, and not the result from one of the rows containing the initial values of aggregate functions.</p>

<p>As opposed to MySQL (and conforming to standard SQL), you can&#39;t get some value of some column that is not in a key or aggregate function (except constant expressions). To work around this, you can use the &#39;any&#39; aggregate function (get the first encountered value) or &#39;min/max&#39;.</p>

<p>Example:</p>

<pre class='text-example'>SELECT
    domainWithoutWWW(URL) AS domain,
    count(),
    any(Title) AS title -- we take the first page title for each domain
FROM hits
GROUP BY domain</pre>

<p>For every different key value encountered, GROUP BY calculates a set of aggregate function values.</p>

<p>GROUP BY is not supported for array columns.</p>

<p>A constant can&#39;t be specified as arguments for aggregate functions. Example: sum(1). Instead of this, you can get rid of the constant. Example: count().</p>


<h5>WITH TOTALS modifier</h5>

<p>If the WITH TOTALS modifier is specified, another row will be calculated. This row will have key columns containing default values (zeros or empty lines), and columns of aggregate functions with the values calculated across all the rows (the &quot;total&quot; values).</p>

<p>This extra row is output in JSON*, TabSeparated*, and Pretty* formats, separately from the other rows. In the other formats, this row is not output.</p>

<p>In JSON* formats, this row is output as a separate &#39;totals&#39; field. In TabSeparated formats, the row comes after the main result, preceded by an empty row (after the other data). In Pretty formats, the row is output as a separate table after the main result.</p>

<p>WITH TOTALS can be run in different ways when HAVING is present. The behavior depends on the &#39;totals_mode&#39; setting.
By default, totals_mode = &#39;<b>before_having</b>&#39;. In this case, &#39;totals&#39; is calculated across all rows, including the ones that don&#39;t pass through HAVING and &#39;max_rows_to_group_by&#39;.</p>

<p>The other alternatives include only the rows that pass through HAVING in &#39;totals&#39;, and behave differently with the setting &#39;max_rows_to_group_by&#39; and &#39;group_by_overflow_mode = &#39;any&#39;&#39;.</p>

<p><b>after_having_exclusive</b> - Don&#39;t include rows that didn&#39;t pass through &#39;max_rows_to_group_by&#39;. In other words, &#39;totals&#39; will have less than or the same number of rows as it would if &#39;max_rows_to_group_by&#39; were omitted.</p>

<p><b>after_having_inclusive</b> - Include all the rows that didn&#39;t pass through &#39;max_rows_to_group_by&#39; in &#39;totals&#39;. In other words, &#39;totals&#39; will have more than or the same number of rows as it would if &#39;max_rows_to_group_by&#39; were omitted.</p>

<p><b>after_having_auto</b> - Count the number of rows that passed through HAVING. If it is more than a certain amount (by default, 50%), include all the rows that didn&#39;t pass through &#39;max_rows_to_group_by&#39; in &#39;totals&#39;. Otherwise, do not include them.</p>

<p><b>totals_auto_threshold</b> - By default, 0.5 is the coefficient for <b>after_having_auto</b>.</p>

<p>If &#39;max_rows_to_group_by&#39; and &#39;group_by_overflow_mode = &#39;any&#39;&#39; are not used, all variations of &#39;after_having&#39; are the same, and you can use any of them (for example, &#39;after_having_auto&#39;).</p>

<p>You can use WITH TOTALS in subqueries, including subqueries in the JOIN clause. In this case, the respective total values are combined.</p>


<h4>HAVING clause</h4>

<p>Allows filtering the result received after GROUP BY, similar to the WHERE clause.
WHERE and HAVING differ in that WHERE is performed before aggregation (GROUP BY), while HAVING is performed after it. If aggregation is not performed, HAVING can&#39;t be used.</p>


<h4>ORDER BY clause</h4>

<p>The ORDER BY clause contains a list of expressions, which can each be assigned DESC or ASC (the sorting direction). If the direction is not specified, ASC is assumed. ASC is sorted in ascending order, and DESC in descending order. The sorting direction applies to a single expression, not to the entire list. Example: <span class='inline-example'>ORDER BY Visits DESC, SearchPhrase</span></p>

<p>For sorting by String values, you can specify collation (comparison). Example: <span class='inline-example'>ORDER BY SearchPhrase COLLATE &#39;tr&#39;</span> - for sorting by keyword in ascending order, using the Turkish alphabet, case insensitive, assuming that strings are UTF-8 encoded. COLLATE can be specified or not for each expression in ORDER BY independently. If ASC or DESC is specified, COLLATE is specified after it. When using COLLATE, sorting is always case-insensitive.

We only recommend using COLLATE for final sorting of a small number of rows, since sorting with COLLATE is less efficient than normal sorting by bytes.</p>

<p>Rows that have identical values for the list of sorting expressions are output in an arbitrary order, which can also be nondeterministic (different each time).
If the ORDER BY clause is omitted, the order of the rows is also undefined, and may be nondeterministic as well.</p>

<p>When floating point numbers are sorted, NaNs are separate from the other values. Regardless of the sorting order, NaNs come at the end. In other words, for ascending sorting they are placed as if they are larger than all the other numbers, while for descending sorting they are placed as if they are smaller than the rest.</p>

<p>Less RAM is used if a small enough LIMIT is specified in addition to ORDER BY. Otherwise, the amount of memory spent is proportional to the volume of data for sorting. For distributed query processing, if GROUP BY is omitted, sorting is partially done on remote servers, and the results are merged on the requestor server. This means that for distributed sorting, the volume of data to sort can be greater than the amount of memory on a single server.</p>

<p>If there is not enough RAM, it is possible to perform sorting in external memory (creating temporary files on a disk). Use the setting <span class='inline-example'>max_bytes_before_external_sort</span> for this purpose. If it is set to 0 (the default), external sorting is disabled. If it is enabled, when the volume of data to sort reaches the specified number of bytes, the collected data is sorted and dumped into a temporary file. After all data is read, all the sorted files are merged and the results are output. Files are written to the /opt/clickhouse/tmp/ directory in the config (by default, but you can use the &#39;tmp_path&#39; parameter to change this setting).</p>

<p>Running a query may use more memory than &#39;max_bytes_before_external_sort&#39;. For this reason, this setting must have a value significantly smaller than &#39;max_memory_usage&#39;. As an example, if your server has 128 GB of RAM and you need to run a single query, set &#39;max_memory_usage&#39; to 100 GB, and &#39;max_bytes_before_external_sort&#39; to 80 GB.</p>

<p>External sorting works much less effectively than sorting in RAM.</p>

<h4>SELECT clause</h4>

<p>The expressions specified in the SELECT clause are analyzed after the calculations for all the clauses listed above are completed.
More specifically, expressions are analyzed that are above the aggregate functions, if there are any aggregate functions. The aggregate functions and everything below them are calculated during aggregation (GROUP BY). These expressions work as if they are applied to separate rows in the result.</p>

<h4>DISTINCT clause</h4>

<p>If DISTINCT is specified, only a single row will remain out of all the sets of fully matching rows in the result.
The result will be the same as if GROUP BY were specified across all the fields specified in SELECT without aggregate functions. But there are several differences from GROUP BY:
- DISTINCT can be applied together with GROUP BY.
- When ORDER BY is omitted and LIMIT is defined, the query stops running immediately after the required number of different rows has been read. In this case, using DISTINCT is much more optimal.
- Data blocks are output as they are processed, without waiting for the entire query to finish running.</p>

<p>DISTINCT is not supported if SELECT has at least one array column.</p>

<h4>LIMIT clause</h4>

<p>LIMIT m allows you to select the first &#39;m&#39; rows from the result.
LIMIT n, m allows you to select the first &#39;m&#39; rows from the result after skipping the first &#39;n&#39; rows.</p>

<p>&#39;n&#39; and &#39;m&#39; must be non-negative integers.</p>

<p>If there isn&#39;t an ORDER BY clause that explicitly sorts results, the result may be arbitrary and nondeterministic.</p>


<h4>UNION ALL clause</h4>

<p>You can use UNION ALL to combine any number of queries. Example:</p>

<pre class='text-example'>
SELECT CounterID, 1 AS table, toInt64(count()) AS c
    FROM test.hits
    GROUP BY CounterID

UNION ALL

SELECT CounterID, 2 AS table, sum(Sign) AS c
    FROM test.visits
    GROUP BY CounterID
    HAVING c > 0
</pre>

<p>Only UNION ALL is supported. The regular UNION (UNION DISTINCT) is not supported. If you need UNION DISTINCT, you can write SELECT DISTINCT from a subquery containing UNION ALL.</p>

<p>Queries that are parts of UNION ALL can be run simultaneously, and their results can be mixed together.</p>

<p>The structure of results (the number and type of columns) must match for the queries, but the column names can differ. In this case, the column names for the final result will be taken from the first query.</p>

<p>Queries that are parts of UNION ALL can&#39;t be enclosed in brackets. ORDER BY and LIMIT are applied to separate queries, not to the final result. If you need to apply a conversion to the final result, you can put all the queries with UNION ALL in a subquery in the FROM clause.</p>


<h4>FORMAT clause</h4>

<p>Specify &#39;FORMAT format&#39; to get data in any specified format.
You can use this for convenience, or for creating dumps. For more information, see the section &quot;Formats&quot;.
If the FORMAT clause is omitted, the default format is used, which depends on both the settings and the interface used for accessing the DB. For the HTTP interface and the command-line client in batch mode, the default format is TabSeparated. For the command-line client in interactive mode, the default format is PrettyCompact (it has attractive and compact tables).</p>

<p>When using the command-line client, data is passed to the client in an internal efficient format. The client independently interprets the FORMAT clause of the query and formats the data itself (thus relieving the network and the server from the load).</p>


<h4>IN operators</h4>

<p>The <span class='inline-example'>IN</span>, <span class='inline-example'>NOT IN</span>, <span class='inline-example'>GLOBAL IN</span>, and <span class='inline-example'>GLOBAL NOT IN</span> operators are covered separately, since their functionality is quite rich.</p>

<p>The left side of the operator is either a single column or a tuple.</p>

<p>Examples:</p>

<pre class='text-example'>SELECT UserID IN (123, 456) FROM ...</pre>
<pre class='text-example'>SELECT (CounterID, UserID) IN ((34, 123), (101500, 456)) FROM ...</pre>

<p>If the left side is a single column that is in the index, and the right side is a set of constants, the system uses the index for processing the query.</p>

<p>Don&#39;t list too many values explicitly (i.e. millions). If a data set is large, put it in a temporary table (for example, see the section &quot;External data for query processing&quot;), then use a subquery.</p>

<p>The right side of the operator can be a set of constant expressions, a set of tuples with constant expressions (shown in the examples above), or the name of a database table or SELECT subquery in brackets.</p>

<p>If the right side of the operator is the name of a table (for example, <span class='inline-example'>UserID IN users</span>), this is equivalent to the subquery <span class='inline-example'>UserID IN (SELECT * FROM users)</span>. Use this when working with external data that is sent along with the query. For example, the query can be sent together with a set of user IDs loaded to the &#39;users&#39; temporary table, which should be filtered.</p>

<p>If the right side of the operator is a table name that has the Set engine (a prepared data set that is always in RAM), the data set will not be created over again for each query.</p>

<p>The subquery may specify more than one column for filtering tuples.
Example:</p>
<pre class='text-example'>SELECT (CounterID, UserID) IN (SELECT CounterID, UserID FROM ...) FROM ...</pre>

<p>The columns to the left and right of the <span class='inline-example'>IN</span> operator should have the same type.</p>

<p>Exception: If there is an array to the left of IN, it checks that at least one array item belongs to the data set.
For example, <span class='inline-example'>[1, 2, 3] IN (3, 4, 5)</span> returns 1. This is somewhat illogical, but it is convenient for implementing certain Yandex.Metrica functionality.</p>

<p>If there is an array to the left of NOT IN, it checks that at least one array item does not belong to the data set.
For example, <span class='inline-example'>[1, 2, 3] NOT IN (3, 4, 5)</span> returns 1. This is completely illogical, so don&#39;t rely on this behavior. We recommend using higher-order functions instead. Example: <span class='inline-example'>arrayAll(x -> x IN (3, 4, 5), [1, 2, 3])</span> returns 0 - it checks whether all the array items belong to the data set.</p>

<p>The IN operator and subquery may occur in any part of the query, including in aggregate functions and lambda functions.
Example:</p>

<pre class='text-example'>SELECT
    EventDate,
    avg(UserID IN
    (
        SELECT UserID
        FROM test.hits
        WHERE EventDate = toDate(&#39;2014-03-17&#39;)
    )) AS ratio
FROM test.hits
GROUP BY EventDate
ORDER BY EventDate ASC

┌──EventDate─┬────ratio─┐
│ 2014-03-17 │        1 │
│ 2014-03-18 │ 0.807696 │
│ 2014-03-19 │ 0.755406 │
│ 2014-03-20 │ 0.723218 │
│ 2014-03-21 │ 0.697021 │
│ 2014-03-22 │ 0.647851 │
│ 2014-03-23 │ 0.648416 │
└────────────┴──────────┘
</pre>
<p>- for each day after March 17th, count the percentage of pageviews made by users who visited the site on March 17th.</p>

<p>A subquery in the IN clause is always run just one time on a single server. There are no dependent subqueries.</p>


<h4>Distributed subqueries</h4>

<p>There are two versions of INs with subqueries (and for JOINs): the regular <span class='inline-example'>IN</span> / <span class='inline-example'>JOIN</span>, and <span class='inline-example'>GLOBAL IN</span> / <span class='inline-example'>GLOBAL JOIN</span>. They differ in how they are run for distributed query processing.</p>

<p>When using the regular <span class='inline-example'>IN</span>, the query is sent to remote servers, and each of them runs the subqueries in the IN or JOIN clause.</p>

<p>When using <span class='inline-example'>GLOBAL IN</span> / <span class='inline-example'>GLOBAL JOIN</span>, first all the subqueries for <span class='inline-example'>GLOBAL IN</span> / <span class='inline-example'>GLOBAL JOIN</span> are run, and the results are collected in temporary tables. Then the temporary tables are sent to each remote server, where the queries are run using this temporary data.</p>

<p>For a non-distributed query, use the regular <span class='inline-example'>IN</span> / <span class='inline-example'>JOIN</span>.</p>


<p>Be careful when using subqueries in the  <span class='inline-example'>IN</span> / <span class='inline-example'>JOIN</span> clauses for distributed query processing.</p>

<p>Let&#39;s look at some examples. Assume that each server in the cluster has a normal <b>local_table</b>. Each server also has a <b>distributed_table</b> table with the <b>Distributed</b> type, which looks at all the servers in the cluster.</p>

<p>For a query to the <b>distributed_table</b>, the query will be sent to all the remote servers and run on them using the <b>local_table</b>.</p>

2336
<p>For example, the query
2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354
<span class='inline-example'>SELECT uniq(UserID) FROM distributed_table</span>
will be sent to all the remote servers as
<span class='inline-example'>SELECT uniq(UserID) FROM local_table</span>
and run on each of them in parallel, until it reaches the stage where intermediate results can be combined. Then the intermediate results will be returned to the requestor server and merged on it, and the final result will be sent to the client.</p>

<p>Now let&#39;s examine a query with IN:
<span class='inline-example'>SELECT uniq(UserID) FROM distributed_table WHERE CounterID = 101500 AND UserID IN (SELECT UserID FROM local_table WHERE CounterID = 34)</span>
- calculates the overlap in the audiences of two websites.</p>

<p>This query will be sent to all the remote servers as
<span class='inline-example'>SELECT uniq(UserID) FROM local_table WHERE CounterID = 101500 AND UserID IN (SELECT UserID FROM local_table WHERE CounterID = 34)</span>
In other words, the data set in the <span class='inline-example'>IN</span> clause will be collected on each server independently, only across the data that is stored locally on each of the servers.</p>

<p>This will work correctly and optimally if you are prepared for this case and have spread data across the cluster servers such that the data for a single UserID resides entirely on a single server. In this case, all the necessary data will be available locally on each server. Otherwise, the result will be inaccurate. We refer to this variation of the query as &quot;local IN&quot;.</p>

<p>To correct how the query works when data is spread randomly across the cluster servers, you could specify <b>distributed_table</b> inside a subquery. The query would look like this:
<span class='inline-example'>SELECT uniq(UserID) FROM distributed_table WHERE CounterID = 101500 AND UserID IN (SELECT UserID FROM distributed_table WHERE CounterID = 34)</span></p>

2355
<p>This query will be sent to all remote servers as
2356
<span class='inline-example'>SELECT uniq(UserID) FROM local_table WHERE CounterID = 101500 AND UserID IN (SELECT UserID FROM distributed_table WHERE CounterID = 34)</span>
2357
Each of the remote servers will start running the subquery. Since the subquery uses a distributed table, each remote server will re-send the subquery to every remote server, as
2358 2359 2360 2361 2362 2363 2364 2365 2366
<span class='inline-example'>SELECT UserID FROM local_table WHERE CounterID = 34</span>
For example, if you have a cluster of 100 servers, executing the entire query will require 10,000 elementary requests, which is generally considered unacceptable.</p>

<p>In such cases, you should always use <span class='inline-example'>GLOBAL IN</span> instead of <span class='inline-example'>IN</span>. Let&#39;s look at how it works for the query
<span class='inline-example'>SELECT uniq(UserID) FROM distributed_table WHERE CounterID = 101500 AND UserID GLOBAL IN (SELECT UserID FROM distributed_table WHERE CounterID = 34)</span></p>

<p>The requestor server will execute the subquery
<span class='inline-example'>SELECT UserID FROM distributed_table WHERE CounterID = 34</span>
and the result will be put in a temporary table in RAM. Then a query will be sent to each remote server as
2367
<span class='inline-example'>SELECT uniq(UserID) FROM local_table WHERE CounterID = 101500 AND UserID GLOBAL IN _data1</span>
2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688
and the temporary table &#39;_data1&#39; will be sent to every remote server together with the query (the name of the temporary table is implementation-defined).</p>

<p>This is more optimal than using the normal IN. However, keep the following points in mind:</p>

<p>1. When creating a temporary table, data is not made unique. To reduce the volume of data transmitted over the network, specify <span class='inline-example'>DISTINCT</span> in the subquery. (You don&#39;t need to do this for a normal IN.)
2. The temporary table will be sent to all the remote servers. Transmission does not account for network topology. For example, if 10 remote servers reside in a datacenter that is very remote in relation to the requestor server, the data will be sent 10 times over the channel to the remote datacenter. Try to avoid large data sets when using <span class='inline-example'>GLOBAL IN</span>.
3. When transmitting data to remote servers, restrictions on network bandwidth are not configurable. You might overload the network.
4. Try to distribute data across servers so that you don&#39;t need to use <span class='inline-example'>GLOBAL IN</span> on a regular basis.
5. If you need to use <span class='inline-example'>GLOBAL IN</span> often, plan the location of the ClickHouse cluster so that a single group of replicas resides in no more than one data center, and there is a fast network between them.</p>

<p>It also makes sense to specify a local table in the <span class='inline-example'>GLOBAL IN</span> clause, in case this local table is only available on the requestor server and you want to use data from it on remote servers.</p>


<h4>Extreme values</h4>

<p>In addition to results, you can also get minimum and maximum values for the results columns. To do this, set the &#39;extremes&#39; setting to &#39;1&#39;. Minimums and maximums are calculated for numeric types, dates, and dates with times. For other columns, the default values are output.</p>

<p>An extra two rows are calculated - the minimums and maximums, respectively. These extra two rows are output in JSON*, TabSeparated*, and Pretty* formats, separate from the other rows. They are not output for other formats.</p>

<p>In JSON* formats, the extreme values are output in a separate &#39;extremes&#39; field. In TabSeparated formats, the row comes after the main result, and after &#39;totals&#39; if present. It is preceded by an empty row (after the other data). In Pretty formats, the row is output as a separate table after the main result, and after &#39;totals&#39; if present.</p>

<p>Extreme values are calculated for rows that have passed through LIMIT. However, when using &#39;LIMIT offset, size&#39;, the rows before &#39;offset&#39; are included in &#39;extremes&#39;. In stream requests, the result may also include a small number of rows that passed through LIMIT.</p>


<h4>Notes</h4>

<p>The GROUP BY and ORDER BY clauses do not support positional arguments. This contradicts MySQL, but conforms to standard SQL.
For example, &#39;GROUP BY 1, 2&#39; will be interpreted as grouping by constants (i.e. aggregation of all rows into one).</p>

<p>You can use synonyms (AS aliases) in any part of a query.</p>

<p>You can put an asterisk in any part of a query instead of an expression. When the query is analyzed, the asterisk is expanded to a list of all table columns (excluding the MATERIALIZED and ALIAS columns). There are only a few cases when using an asterisk is justified:
- When creating a table dump.
- For tables containing just a few columns, such as system tables.
- For getting information about what columns are in a table. In this case, set &#39;LIMIT 1&#39;. But it is better to use the <b>DESC TABLE</b> query.
- When there is strong filtration on a small number of columns using PREWHERE.
- In subqueries (since columns that aren&#39;t needed for the external query are excluded from subqueries).
In all other cases, we don&#39;t recommend using the asterisk, since it only gives you the drawbacks of a columnar DBMS instead of the advantages.</p>


</div>
<div class='island'>
<h1>External data for query processing</h1>
</div>
<div class='island'>

<p>ClickHouse allows sending a server the data that is needed for processing a query, together with a SELECT query. This data is put in a temporary table (see the section &quot;Temporary tables&quot;) and can be used in the query (for example, in IN operators).</p>

<p>For example, if you have a text file with important user identifiers, you can upload it to the server along with a query that uses filtration by this list.</p>

<p>If you need to run more than one query with a large volume of external data, don&#39;t use this feature. It is better to upload the data to the DB ahead of time.</p>

<p>External data can be uploaded using the command-line client (in non-interactive mode), or using the HTTP interface.</p>

<p>In the command-line client, you can specify a parameters section in the format</p>

<pre class='text-example'>--external --file=... [--name=...] [--format=...] [--types=...|--structure=...]</pre>

<p>You may have multiple sections like this, for the number of tables being transmitted.

<b>--external</b> - Marks the beginning of the section.
<b>--file</b> - Path to the file with the table dump, or <span class='inline-example'>-</span>, which refers to stdin.
Only a single table can be retrieved from stdin.</p>

<p>The following parameters are optional:
<b>--name</b> - Name of the table. If omitted, <span class='inline-example'>_data</span> is used.
<b>--format</b> - Data format in the file. If omitted, <span class='inline-example'>TabSeparated</span> is used.</p>

<p>One of the following parameters is required:
<b>--types</b> - A comma-separated list of column types. For example, <span class='inline-example'>UInt64,String</span>. Columns will be named <span class='inline-example'>_1</span>, <span class='inline-example'>_2</span>, ...
<b>--structure</b> - Table structure, in the format <span class='inline-example'>UserID UInt64, URL String</span>. Defines the column names and types.</p>

<p>The files specified in <span class='inline-example'>file</span> will be parsed by the format specified in <span class='inline-example'>format</span>, using the data types specified in <span class='inline-example'>types</span> or <span class='inline-example'>structure</span>. The table will be uploaded to the server and accessible there as a temporary table with the name <span class='inline-example'>name</span>.</p>

<p>Examples:</p>

<pre class='text-example'>echo -ne &quot;1\n2\n3\n&quot; | clickhouse-client --query=&quot;SELECT count() FROM test.visits WHERE TraficSourceID IN _data&quot; --external --file=- --types=Int8
849897
</pre>

<pre class='text-example'>cat /etc/passwd | sed &#39;s/:/\t/g&#39; | clickhouse-client --query=&quot;SELECT shell, count() AS c FROM passwd GROUP BY shell ORDER BY c DESC&quot; --external --file=- --name=passwd --structure=&#39;login String, unused String, uid UInt16, gid UInt16, comment String, home String, shell String&#39;
/bin/sh 20
/bin/false      5
/bin/bash       4
/usr/sbin/nologin       1
/bin/sync       1
</pre>

<p>When using the HTTP interface, external data is passed in the multipart/form-data format. Each table is transmitted as a separate file. The table name is taken from the file name. The &#39;query_string&#39; passes the parameters &#39;<i>name</i>_format&#39;, &#39;<i>name</i>_types&#39;, and &#39;<i>name</i>_structure&#39;, where <i>name</i> is the name of the table that these parameters correspond to. The meaning of the parameters is the same as when using the command-line client.</p>

<p>Example:</p>

<pre class='text-example' style='overflow: scroll;'>cat /etc/passwd | sed &#39;s/:/\t/g&#39; > passwd.tsv

curl -F &#39;passwd=@passwd.tsv;&#39; &#39;http://localhost:8123/?query=SELECT+shell,+count()+AS+c+FROM+passwd+GROUP+BY+shell+ORDER+BY+c+DESC&amp;passwd_structure=login+String,+unused+String,+uid+UInt16,+gid+UInt16,+comment+String,+home+String,+shell+String&#39;
/bin/sh 20
/bin/false      5
/bin/bash       4
/usr/sbin/nologin       1
/bin/sync       1
</pre>

<p>For distributed query processing, the temporary tables are sent to all the remote servers.</p>

</div>
<div class='island'>
<h1>Table engines</h1>
</div>
<div class='island'>

<p>The table engine (type of table) determines:
- How and where data is stored - where to write it to, and where to read it from.
- Which queries are supported, and how.
- Concurrent data access.
- Use of indexes, if present.
- Whether multithreaded request execution is possible.
- Data replication.
- When reading data, the engine is only required to extract the necessary set of columns. However, in some cases, the query may be partially processed inside the table engine.</p>

<p>Note that for most serious tasks, you should use engines from the MergeTree family.</p>


<h2>TinyLog</h2>

<p>The simplest table engine, which stores data on a disk.
Each column is stored in a separate compressed file.
When writing, data is appended to the end of files.
Concurrent data access is not restricted in any way:
- If you are simultaneously reading from a table and writing to it in a different query, the read operation will complete with an error.
- If you are writing to a table in multiple queries simultaneously, the data will be broken.
The typical way to use this table is write-once: first just write the data one time, then read it as many times as needed.
Queries are executed in a single stream. In other words, this engine is intended for relatively small tables (recommended up to 1,000,000 rows).
It makes sense to use this table engine if you have many small tables, since it is simpler than the Log engine (fewer files need to be opened).
The situation when you have a large number of small tables guarantees poor productivity, but may already be used when working with another DBMS, and you may find it easier to switch to using TinyLog types of tables.
Indexes are not supported.</p>

<p>In Yandex.Metrica, TinyLog tables are used for intermediary data that is processed in small batches.</p>


<h2>Log</h2>

<p>Log differs from TinyLog in that a small file of &quot;marks&quot; resides with the column files. These marks are written on every data block and contain offsets - where to start reading the file in order to skip the specified number of rows. This makes it possible to read table data in multiple threads. For concurrent data access, the read operations can be performed simultaneously, while write operations block reads and each other.
The Log engine does not support indexes. Similarly, if writing to a table failed, the table is broken, and reading from it returns an error. The Log engine is appropriate for temporary data, write-once tables, and for testing or demonstration purposes.</p>


<h2>Memory</h2>

<p>The Memory engine stores data in RAM, in uncompressed form. Data is stored in exactly the same form as it is received when read. In other words, reading from this table is completely free.
Concurrent data access is synchronized. Locks are short: read and write operations don&#39;t block each other.
Indexes are not supported. Reading is parallelized.
Maximal productivity (over 10 GB/sec) is reached on simple queries, because there is no reading from the disk, decompressing, or deserializing data. (We should note that in many cases, the productivity of the MergeTree engine is almost as high.)
When restarting a server, data disappears from the table and the table becomes empty.
Normally, using this table engine is not justified. However, it can be used for tests, and for tasks where maximum speed is required on a relatively small number of rows (up to approximately 100,000,000).</p>

<p>The Memory engine is used by the system for temporary tables with external query data (see the section &quot;External data for processing a query&quot;), and for implementing GLOBAL IN (see the section &quot;IN operators&quot;).</p>


<h2>Merge</h2>

<p>The Merge engine (not to be confused with MergeTree) does not store data itself, but allows reading from any number of other tables simultaneously.
Reading is automatically parallelized. Writing to a table is not supported. When reading, the indexes of tables that are actually being read are used, if they exist.
The Merge engine accepts parameters: the database name and a regular expression for tables. Example:</p>

<pre class='text-example'>Merge(hits, &#39;^WatchLog&#39;)</pre>

<p>- Data will be read from the tables in the &#39;hits&#39; database with names that match the regex &#39;^WatchLog&#39;.</p>

<p>Instead of the database name, you can use a constant expression that returns a string. For example, <span class='inline-example'>currentDatabase()</span>.</p>

<p>Regular expressions are re2 (similar to PCRE), case-sensitive. See the notes about escaping symbols in regular expressions in the &quot;match&quot; section.</p>

<p>When selecting tables to read, the Merge table itself will not be selected, even if it matches the regex. This is to avoid loops.
It is possible to create two Merge tables that will endlessly try to read each others&#39; data. But don&#39;t do this.</p>

<p>The typical way to use the Merge engine is for working with a large number of TinyLog tables as if with a single table.</p>

<h3>Virtual columns</h3>

<p>Virtual columns are columns that are provided by the table engine, regardless of the table definition. In other words, these columns are not specified in CREATE TABLE, but they are accessible for SELECT.</p>

<p>Virtual columns differ from normal columns in the following ways:
- They are not specified in table definitions.
- Data can&#39;t be added to them with INSERT.
- When using INSERT without specifying the list of columns, virtual columns are ignored.
- They are not selected when using the asterisk (SELECT *).
- Virtual columns are not shown in SHOW CREATE TABLE and DESC TABLE queries.</p>

<p>A Merge table contains the virtual column <b>_table</b> of the String type. (If the table already has a &#39;_table&#39; column, the virtual column is named &#39;_table1&#39;, and if it already has &#39;_table1&#39;, it is named &#39;_table2&#39;, and so on.) It contains the name of the table that data was read from.</p>

<p>If the WHERE or PREWHERE clause contains conditions for the &#39;_table&#39; column that do not depend on other table columns (as one of the conjunction elements, or as an entire expression), these conditions are used as an index. The conditions are performed on a data set of table names to read data from, and the read operation will be performed from only those tables that the condition was triggered on.</p>


<h2>Distributed</h2>

<p>The Distributed engine does not store data itself, but allows distributed query processing on multiple servers.
Reading is automatically parallelized. During a read, the table indexes on remote servers are used, if there are any.
The Distributed engine accepts parameters: the cluster name in the server&#39;s config file, the name of a remote database, the name of a remote table, and (optionally) a sharding key.
Example:</p>

<pre class='text-example'>Distributed(calcs, default, hits[, sharding_key])</pre>

<p>- Data will be read from all servers in the &#39;calcs&#39; cluster, from the &#39;default.hits&#39; table located on every server in the cluster.
Data is not only read, but is partially processed on the remote servers (to the extent that this is possible).
For example, for a query with GROUP BY, data will be aggregated on remote servers, and the intermediate states of aggregate functions will be sent to the requestor server. Then data will be further aggregated.</p>

<p>Instead of the database name, you can use a constant expression that returns a string. For example, <span class='inline-example'>currentDatabase()</span>.</p>

<p>calcs - The cluster name in the server&#39;s config file.</p>

<p>Clusters are set like this:</p>

<pre class='text-example'>
&lt;!-- Groups of remote servers that can be included in Distributed tables. -->
&lt;remote_servers>
	&lt;test>
		&lt;node>
			&lt;host>example01-01-1&lt;/host>
			&lt;port>9000&lt;/port>
			&lt;weight>1&lt;/weight> &lt;!-- Optional. Shard weight when writing data. By default, 1.-->
		&lt;/node>
		&lt;node>
			&lt;host>example01-01-2&lt;/host>
			&lt;port>9001&lt;/port>
		&lt;/node>
	&lt;/test>
&lt;/remote_servers>
</pre>

<p>Here a cluster with the name &#39;test&#39; is defined, which consists of two servers (shards).</p>

<p>You can also define a cluster consisting of shards and replicas:</p>

<pre class='text-example'>
&lt;remote_servers>
	&lt;logs>
		&lt;shard>
			&lt;!-- Optional. Shard weight when writing data. By default, 1. -->
			&lt;weight>1&lt;/weight>
			&lt;!-- Optional. Whether to write data to just one of the replicas. By default, false - write data to all of the replicas. -->
			&lt;internal_replication>false&lt;/internal_replication>
			&lt;replica>
				&lt;host>example01-01-1&lt;/host>
				&lt;port>9000&lt;/port>
			&lt;/replica>
			&lt;replica>
				&lt;host>example01-01-2&lt;/host>
				&lt;port>9000&lt;/port>
			&lt;/replica>
		&lt;/shard>
		&lt;shard>
			&lt;weight>2&lt;/weight>
			&lt;internal_replication>false&lt;/internal_replication>
			&lt;replica>
				&lt;host>example01-02-1&lt;/host>
				&lt;port>9000&lt;/port>
			&lt;/replica>
			&lt;replica>
				&lt;host>example01-02-2&lt;/host>
				&lt;port>9000&lt;/port>
			&lt;/replica>
		&lt;/shard>
	&lt;/logs>
&lt;/remote_servers>
</pre>

<p>Here a cluster is defined with the name &#39;logs&#39; that consists of two shards, each of which contains two replicas. Shards refer to the servers that contain different parts of the data (in order to read all the data, you must access all the shards).
Replicas are duplicating servers (in order to read all the data, you can access the data on any one of the replicas).</p>

<p>For each server, there are several parameters: mandatory: 'host', 'port', and optional: 'user', 'password'.
<b>host</b> - address of remote server. May be specified as domain name or IPv4 or IPv6 address. If you specify domain, server will perform DNS lookup at startup, and result will be cached till server shutdown. If DNS request is failed, server won't start. If you are changing DNS records, restart the server for new records to take effect.
<b>port</b> - TCP-port for interserver communication (tcp_port in configuration file, usually 9000). Don't get confused with http_port.
<b>user</b> - user name to connect to remote server. By default user is 'default'. This user must have access rights to connect to remote server. Access rights are managed in users.xml configuration file. For additional info, consider "Access rights" section.
<b>password</b> - password to log in to remote server, in plaintext. Default is empty string.</p>

<p>When specifying replicas, one of the available replicas will be selected for each of the shards when reading. You can configure the algorithm for load balancing (the preference for which replica to access) - see the &#39;load_balancing&#39; setting.
If the connection with the server is not established, there will be an attempt to connect with a short timeout. If the connection failed, the next replica will be selected, and so on for all the replicas. If the connection attempt failed for all the replicas, the attempt will be repeated the same way, several times.
This works in favor of resiliency, but does not provide complete fault tolerance: a remote server might accept the connection, but might not work, or work poorly.</p>

<p>You can specify just one of the shards (in this case, query processing should be called remote, rather than distributed) or up to any number of shards. In each shard, you can specify from one to any number of replicas. You can specify a different number of replicas for each shard.</p>

<p>When specifying a single replica for a shard, this is equivalent to the first case, except multiple connection attempts are made for each server if necessary. You can always use the second type.</p>

<p>You can specify as many clusters as you wish in the configuration.</p>

<p>To view your clusters, use the &#39;system.clusters&#39; table.</p>

<p>The Distributed engine allows working with a cluster like a local server. However, the cluster is inextensible: you must write its configuration in the server config file (even better, for all the cluster&#39;s servers). The system does not transfer data between servers itself.</p>

<p>There is no support for Distributed tables that look at other Distributed tables (except in cases when a Distributed table only has one shard). As an alternative, make the Distributed table look at the &quot;final&quot; tables.</p>

<p>The Distributed engine requires writing clusters to the config file. Adding clusters and servers requires restarting. If you need to send a query to an unknown set of shards and replicas each time, you don&#39;t need to create a Distributed table - use the &#39;remote&#39; table function instead. See the section &quot;Table functions&quot;.</p>

<p>There are two methods for writing data to a cluster:</p>

<p>First, you can define which servers to write which data to, and perform the write directly on each shard. In other words, perform INSERT in the tables that the distributed table &quot;looks at&quot;.
This is the most flexible solution - you can use any sharding scheme, which could be non-trivial due to the requirements of the subject area.
This is also the most optimal solution, since data can be written to different shards completely independently.</p>

<p>Second, you can perform INSERT in a Distributed table. In this case, the table will distribute the inserted data across servers itself.
In order to write to a Distributed table, it must have a sharding key set (the last parameter). In addition, if there is only one shard, the write operation works without specifying the sharding key, since it doesn&#39;t have any meaning in this case.</p>

<p>Each shard can have a weight defined in the config file. By default, the weight is equal to one. Data is distributed across shards in the amount proportional to the shard weight. For example, if there are two shards and the first has a weight of 9 while the second has a weight of 10, the first will be sent 9 / 19 parts of the rows, and the second will be sent 10 / 19.</p>

<p>Each shard can have the &#39;internal_replication&#39; parameter defined in the config file.</p>

<p>If this parameter is set to &#39;true&#39;, the write operation selects the first healthy replica and writes data to it. Use this alternative if the Distributed table &quot;looks at&quot; replicated tables. In other words, if the table where data will be written is going to replicate them itself.</p>

<p>If it is set to &#39;false&#39; (the default), data is written to all replicas. In essence, this means that the Distributed table replicates data itself. This is worse than using replicated tables, because the consistency of replicas is not checked, and over time they will contain slightly different data.</p>

<p>To select the shard that a row of data is sent to, the sharding expression is analyzed, and its remainder is taken from dividing it by the total weight of the shards. The row is sent to the shard that corresponds to the half-interval of the remainders from &#39;prev_weight&#39; to &#39;prev_weights + weight&#39;, where &#39;prev_weights&#39; is the total weight of the shards with the smallest number, and &#39;weight&#39; is the weight of this shard. For example, if there are two shards, and the first has a weight of 9 while the second has a weight of 10, the row will be sent to the first shard for the remainders from the range [0, 9), and to the second for the remainders from the range [10, 19).</p>

<p>The sharding expression can be any expression from constants and table columns that returns an integer. For example, you can use the expression &#39;rand()&#39; for random distribution of data, or &#39;UserID&#39; for distribution by the remainder from dividing the user&#39;s ID (then the data of a single user will reside on a single shard, which simplifies running IN and JOIN by users). If one of the columns is not distributed evenly enough, you can wrap it in a hash function: intHash64(UserID).</p>

<p>A simple remainder from division is a limited solution for sharding and isn&#39;t always appropriate. It works for medium and large volumes of data (dozens of servers), but not for very large volumes of data (hundreds of servers or more). In the latter case, use the sharding scheme required by the subject area, rather than using entries in Distributed tables.</p>

<p>We&#39;ll note again that a Distributed table can&#39;t automatically re-shard data. In many cases, you can do without it. SELECT queries are sent to all the shards, and work regardless of how data is distributed across the shards (they can be distributed completely randomly). When you add a new shard, you don&#39;t have to transfer the old data to it. You can write new data with a heavier weight - the data will be distributed slightly unevenly, but queries will work correctly and efficiently.</p>

<p>You should be concerned about the sharding scheme in the following cases:
- Queries are used that require joining data (IN or JOIN) by a specific key. If data is sharded by this key, you can use local IN or JOIN instead of GLOBAL IN or GLOBAL JOIN, which is much more efficient.
- A large number of servers is used (hundreds or more) with a large number of small queries (queries of individual clients - websites, advertisers, or partners). In order for the small queries to not affect the entire cluster, it makes sense to locate data for a single client on a single shard. Alternatively, as we&#39;ve done in Yandex.Metrica, you can set up bi-level sharding: divide the entire cluster into &quot;layers&quot;, where a layer may consist of multiple shards. Data for a single client is located on a single layer, but shards can be added to a layer as necessary, and data is randomly distributed within them. Distributed tables are created for each layer, and a single shared distributed table is created for global queries.</p>

2689
<p>Data is written asynchronously. For an INSERT to a Distributed table, the data block is just written to the local file system. The data is sent to the remote servers in the background as soon as possible. You should check whether data is sent successfully by checking the list of files (data waiting to be sent) in the table directory:
2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840
/opt/clickhouse/data/<i>database</i>/<i>table</i>/.</p>

<p>If the server ceased to exist or had a rough restart (for example, after a device failure) after an INSERT to a Distributed table, the inserted data might be lost. If a damaged data part is detected in the table directory, it is transferred to the &#39;broken&#39; subdirectory and no longer used.</p>


<h2>MergeTree</h2>

<p>The MergeTree engine supports an index by primary key and by date, and provides the possibility to update data in real time.
This is the most advanced table engine in ClickHouse. Don&#39;t confuse it with the Merge engine.</p>

<p>The engine accepts parameters: the name of a Date type column containing the date, a sampling expression (optional), a tuple that defines the table&#39;s primary key, and the index granularity.
Example:</p>

<p>Example without sampling support:</p>
<pre class='text-example'>MergeTree(EventDate, (CounterID, EventDate), 8192)</pre>

<p>Example with sampling support:</p>
<pre class='text-example'>MergeTree(EventDate, intHash32(UserID), (CounterID, EventDate, intHash32(UserID)), 8192)</pre>

<p>A MergeTree type table must have a separate column containing the date. In this example, it is the &#39;EventDate&#39; column. The type of the date column must be &#39;Date&#39; (not &#39;DateTime&#39;).</p>

<p>The primary key may be a tuple from any expressions (usually this is just a tuple of columns), or a single expression.</p>

<p>The sampling expression (optional) can be any expression. It must also be present in the primary key. The example uses a hash of user IDs to pseudo-randomly disperse data in the table for each CounterID and EventDate. In other words, when using the SAMPLE clause in a query, you get an evenly pseudo-random sample of data for a subset of users.</p>

<p>The table is implemented as a set of parts. Each part is sorted by the primary key. In addition, each part has the minimum and maximum date assigned. When inserting in the table, a new sorted part is created. The merge process is periodically initiated in the background. When merging, several parts are selected, usually the smallest ones, and then merged into one large sorted part.</p>

<p>In other words, incremental sorting occurs when inserting to the table. Merging is implemented so that the table always consists of a small number of sorted parts, and the merge itself doesn&#39;t do too much work.</p>

<p>During insertion, data belonging to different months is separated into different parts. The parts that correspond to different months are never combined. The purpose of this is to provide local data modification (for ease in backups).</p>

<p>Parts are combined up to a certain size threshold, so there aren&#39;t any merges that are too long.</p>

<p>For each part, an index file is also written. The index file contains the primary key value for every &#39;index_granularity&#39; row in the table. In other words, this is an abbreviated index of sorted data.</p>

<p>For columns, &quot;marks&quot; are also written to each &#39;index_granularity&#39; row so that data can be read in a specific range.</p>

<p>When reading from a table, the SELECT query is analyzed for whether indexes can be used. An index can be used if the WHERE or PREWHERE clause has an expression (as one of the conjunction elements, or entirely) that represents an equality or inequality comparison operation, or if it has IN above columns that are in the primary key or date, or Boolean operators over them.</p>

<p>Thus, it is possible to quickly run queries on one or many ranges of the primary key. In the example given, queries will work quickly for a specific counter, for a specific counter and range of dates, for a specific counter and date, for multiple counters and a range of dates, and so on.</p>

<pre class='text-example'>SELECT count() FROM table WHERE EventDate = toDate(now()) AND CounterID = 34</pre>
<pre class='text-example'>SELECT count() FROM table WHERE EventDate = toDate(now()) AND (CounterID = 34 OR CounterID = 42)</pre>
<pre class='text-example'>SELECT count() FROM table WHERE ((EventDate >= toDate(&#39;2014-01-01&#39;) AND EventDate &lt;= toDate(&#39;2014-01-31&#39;)) OR EventDate = toDate(&#39;2014-05-01&#39;)) AND CounterID IN (101500, 731962, 160656) AND (CounterID = 101500 OR EventDate != toDate(&#39;2014-05-01&#39;))</pre>

<p>All of these cases will use the index by date and by primary key. The index is used even for complex expressions. Reading from the table is organized so that using the index can&#39;t be slower than a full scan.</p>

<p>In this example, the index can&#39;t be used:</p>
<pre class='text-example'>SELECT count() FROM table WHERE CounterID = 34 OR URL LIKE &#39;%upyachka%&#39;</pre>

<p>The index by date only allows reading those parts that contain dates from the desired range. However, a data part may contain data for many dates (up to an entire month), while within a single part the data is ordered by the primary key, which might not contain the date as the first column. Because of this, using a query with only a date condition that does not specify the primary key prefix will cause more data to be read than for a single date.</p>

<p>For concurrent table access, we use multi-versioning. In other words, when a table is simultaneously read and updated, data is read from a set of parts that is current at the time of the query. There are no lengthy locks. Inserts do not get in the way of read operations.</p>

<p>Reading from a table is automatically parallelized.</p>

<p>The OPTIMIZE query is supported, which calls an extra merge step.</p>

<p>You can use a single large table and continually add data to it in small chunks - this is what MergeTree is intended for.</p>

<p>Data replication is possible for all types of tables in the MergeTree family (see the section &quot;Data replication&quot;).</p>


<h2>CollapsingMergeTree</h2>

<p>This engine differs from MergeTree in that it allows automatic deletion, or &quot;collapsing&quot; certain pairs of rows when merging.</p>

<p>Yandex.Metrica has normal logs (such as hit logs) and change logs. Change logs are used for incrementally calculating statistics on data that is constantly changing. Examples are the log of session changes, or logs of changes to user histories. Sessions are constantly changing in Yandex.Metrica. For example, the number of hits per session increases. We refer to changes in any object as a pair (?old values, ?new values). Old values may be missing if the object was created. New values may be missing if the object was deleted. If the object was changed, but existed previously and was not deleted, both values are present. In the change log, one or two entries are made for each change. Each entry contains all the attributes that the object has, plus a special attribute for differentiating between the old and new values. When objects change, only the new entries are added to the change log, and the existing ones are not touched.</p>

<p>The change log makes it possible to incrementally calculate almost any statistics. To do this, we need to consider &quot;new&quot; rows with a plus sign, and &quot;old&quot; rows with a minus sign. In other words, incremental calculation is possible for all statistics whose algebraic structure contains an operation for taking the inverse of an element. This is true of most statistics. We can also calculate &quot;idempotent&quot; statistics, such as the number of unique visitors, since the unique visitors are not deleted when making changes to sessions.</p>

<p>This is the main concept that allows Yandex.Metrica to work in real time.</p>

<p>CollapsingMergeTree accepts an additional parameter - the name of an Int8-type column that contains the row&#39;s &quot;sign&quot;. Example:</p>

<pre class='text-example'>CollapsingMergeTree(EventDate, (CounterID, EventDate, intHash32(UniqID), VisitID), 8192, Sign)</pre>

<p>Here, &#39;Sign&#39; is a column containing -1 for &quot;old&quot; values and 1 for &quot;new&quot; values.</p>

<p>When merging, each group of consecutive identical primary key values (columns for sorting data) is reduced to no more than one row with the column value &#39;sign_column = -1&#39; (the &quot;negative row&quot;) and no more than one row with the column value &#39;sign_column = 1&#39; (the &quot;positive row&quot;). In other words, entries from the change log are collapsed.</p>

<p>If the number of positive and negative rows matches, the first negative row and the last positive row are written.
If there is one more positive row than negative rows, only the last positive row is written.
If there is one more negative row than positive rows, only the first negative row is written.
Otherwise, there will be a logical error and none of the rows will be written. (A logical error can occur if the same section of the log was accidentally inserted more than once. The error is just recorded in the server log, and the merge continues.)</p>

<p>Thus, collapsing should not change the results of calculating statistics.
Changes are gradually collapsed so that in the end only the last value of almost every object is left.
Compared to MergeTree, the CollapsingMergeTree engine allows a multifold reduction of data volume.</p>

<p>There are several ways to get completely &quot;collapsed&quot; data from a CollapsingMergeTree table:
1. Write a query with GROUP BY and aggregate functions that accounts for the sign. For example, to calculate quantity, write &#39;sum(Sign)&#39; instead of &#39;count()&#39;. To calculate the sum of something, write &#39;sum(Sign * x)&#39; instead of &#39;sum(x)&#39;, and so on, and also add &#39;HAVING sum(Sign) > 0&#39;. Not all amounts can be calculated this way. For example, the aggregate functions &#39;min&#39; and &#39;max&#39; can&#39;t be rewritten.
2. If you must extract data without aggregation (for example, to check whether rows are present whose newest values match certain conditions), you can use the FINAL modifier for the FROM clause. This approach is significantly less efficient.</p>


<h2>SummingMergeTree</h2>

<p>This engine differs from MergeTree in that it totals data while merging.</p>

<pre class='text-example'>SummingMergeTree(EventDate, (OrderID, EventDate, BannerID, ...), 8192)</pre>

<p>The columns to total are implicit. When merging, all rows with the same primary key value (in the example, OrderId, EventDate, BannerID, ...) have their values totaled in numeric columns that are not part of the primary key.</p>

<pre class='text-example'>SummingMergeTree(EventDate, (OrderID, EventDate, BannerID, ...), 8192, (Shows, Clicks, Cost, ...))</pre>

<p>The columns to total are set explicitly (the last parameter - Shows, Clicks, Cost, ...). When merging, all rows with the same primary key value have their values totaled in the specified columns. The specified columns also must be numeric and must not be part of the primary key.</p>

<p>If the values were null in all of these columns, the row is deleted. (The exception is cases when the data part would not have any rows left in it.)</p>

<p>For the other rows that are not part of the primary key, the first value that occurs is selected when merging.</p>

<p>Summation is not performed for a read operation. If it is necessary, write the appropriate GROUP BY.</p>

<p>In addition, a table can have nested data structures that are processed in a special way.
If the name of a nested table ends in &#39;Map&#39; and it contains at least two columns that meet the following criteria:
- for the first table, numeric ((U)IntN, Date, DateTime), we&#39;ll refer to it as &#39;key&#39;
- for other tables, arithmetic ((U)IntN, Float32/64), we&#39;ll refer to it as &#39;(values...)&#39;
then this nested table is interpreted as a mapping of key => (values...), and when merging its rows, the elements of two data sets are merged by &#39;key&#39; with a summation of the corresponding (values...).
Examples:</p>

<pre class='text-example'>
[(1, 100)] + [(2, 150)] -> [(1, 100), (2, 150)]
[(1, 100)] + [(1, 150)] -> [(1, 250)]
[(1, 100)] + [(1, 150), (2, 150)] -> [(1, 250), (2, 150)]
[(1, 100), (2, 150)] + [(1, -100)] -> [(2, 150)]
</pre>

<p>For nested data structures, you don&#39;t need to specify the columns as a list of columns for totaling.</p>

<p>This table engine is not particularly useful. Remember that when saving just pre-aggregated data, you lose some of the system&#39;s advantages.</p>


<h2>AggregatingMergeTree</h2>

<p>This engine differs from MergeTree in that the merge combines the states of aggregate functions stored in the table for rows with the same primary key value.</p>

<p>In order for this to work, it uses the AggregateFunction data type and the -State and -Merge modifiers for aggregate functions. Let&#39;s examine it more closely.</p>

<p>There is an AggregateFunction data type, which is a parametric data type. As parameters, the name of the aggregate function is passed, then the types of its arguments.
Examples:</p>

<pre class='text-example'>CREATE TABLE t
(
    column1 AggregateFunction(uniq, UInt64),
    column2 AggregateFunction(anyIf, String, UInt8),
    column3 AggregateFunction(quantiles(0.5, 0.9), UInt64)
) ENGINE = ...
</pre>

<p>This type of column stores the state of an aggregate function.</p>

2841
<p>To get this type of value, use aggregate functions with the &#39;State&#39; suffix.
2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622
Example: uniqState(UserID), quantilesState(0.5, 0.9)(SendTiming) - in contrast to the corresponding &#39;uniq&#39; and &#39;quantiles&#39; functions, these functions return the state, rather than the prepared value. In other words, they return an AggregateFunction type value.</p>

<p>An AggregateFunction type value can&#39;t be output in Pretty formats. In other formats, these types of values are output as implementation-specific binary data. The AggregateFunction type values are not intended for output or saving in a dump.</p>

<p>The only useful thing you can do with AggregateFunction type values is combine the states and get a result, which essentially means to finish aggregation. Aggregate functions with the &#39;Merge&#39; suffix are used for this purpose.
Example: uniqMerge(UserIDState), where UserIDState has the AggregateFunction type.</p>

<p>In other words, an aggregate function with the &#39;Merge&#39; suffix takes a set of states, combines them, and returns the result.
As an example, these two queries return the same result:</p>

<pre class='text-example'>SELECT uniq(UserID) FROM table</pre>

<pre class='text-example'>SELECT uniqMerge(state) FROM (SELECT uniqState(UserID) AS state FROM table GROUP BY RegionID)</pre>

<p>There is an AggregatingMergeTree engine. Its job during a merge is to combine the states of aggregate functions from different table rows with the same primary key value.</p>

<p>You can&#39;t use a normal INSERT to insert a row in a table containing AggregateFunction columns, because you can&#39;t explicitly define the AggregateFunction value. Instead, use INSERT SELECT with &#39;-State&#39; aggregate functions for inserting data.</p>

<p>With SELECT from an AggregatingMergeTree table, use GROUP BY and aggregate functions with the &#39;-Merge&#39; modifier in order to complete data aggregation.</p>

<p>You can use AggregatingMergeTree tables for incremental data aggregation, including for aggregated materialized views.</p>

<p>Example:
Creating a materialized AggregatingMergeTree view that tracks the &#39;test.visits&#39; table:</p>

<pre class='text-example'>
CREATE MATERIALIZED VIEW test.basic
ENGINE = AggregatingMergeTree(StartDate, (CounterID, StartDate), 8192)
AS SELECT
    CounterID,
    StartDate,
    sumState(Sign)    AS Visits,
    uniqState(UserID) AS Users
FROM test.visits
GROUP BY CounterID, StartDate;
</pre>

<p>Inserting data in the &#39;test.visits&#39; table. Data will also be inserted in the view, where it will be aggregated:</p>

<pre class='text-example'>
INSERT INTO test.visits ...
</pre>

<p>Performing SELECT from the view using GROUP BY to finish data aggregation:</p>

<pre class='text-example'>
SELECT
    StartDate,
    sumMerge(Visits) AS Visits,
    uniqMerge(Users) AS Users
FROM test.basic
GROUP BY StartDate
ORDER BY StartDate;
</pre>

<p>You can create a materialized view like this and assign a normal view to it that finishes data aggregation.</p>

<p>Note that in most cases, using AggregatingMergeTree is not justified, since queries can be run efficiently enough on non-aggregated data.</p>


<h2>Null</h2>

<p>When writing to a Null table, data is ignored. When reading from a Null table, the response is empty.</p>

<p>However, you can create a materialized view on a Null table, so the data written to the table will end up in the view.</p>


<h2>View</h2>

<p>Used for implementing views (for more information, see the CREATE VIEW query). It does not store data, but only stores the specified SELECT query. When reading from a table, it runs this query (and deletes all unnecessary columns from the query).</p>


<h2>MaterializedView</h2>

<p>Used for implementing materialized views (for more information, see CREATE MATERIALIZED VIEW). For storing data, it uses a different engine that was specified when creating the view. When reading from a table, it just uses this engine.</p>


<h2>Set</h2>

<p>A data set that is always in RAM. It is intended for use on the right side of the IN operator (see the section &quot;IN operators&quot;).</p>

<p>You can use INSERT to insert data in the table. New elements will be added to the data set, while duplicates will be ignored.
But you can&#39;t perform SELECT from the table. The only way to retrieve data is by using it in the right half of the IN operator.</p>

<p>Data is always located in RAM. For INSERT, the blocks of inserted data are also written to the directory of tables on the disk. When starting the server, this data is loaded to RAM. In other words, after restarting, the data remains in place.</p>

<p>For a rough server restart, the block of data on the disk might be lost or damaged. In the latter case, you may need to manually delete the file with damaged data.</p>


<h2>Join</h2>

<p>A prepared data structure for JOIN that is always located in RAM.</p>

<pre class='text-example'>Join(ANY|ALL, LEFT|INNER, k1[, k2, ...])</pre>

<p>Engine parameters:  ANY|ALL - strictness, and LEFT|INNER - the type. These parameters are set without quotes and must match the JOIN that the table will be used for. k1, k2, ... are the key columns from the USING clause that the join will be made on.</p>

<p>The table can&#39;t be used for GLOBAL JOINs.</p>

<p>You can use INSERT to add data to the table, similar to the Set engine. For ANY, data for duplicated keys will be ignored. For ALL, it will be counted. You can&#39;t perform SELECT directly from the table. The only way to retrieve data is to use it as the &quot;right-hand&quot; table for JOIN.</p>

<p>Storing data on the disk is the same as for the Set engine.</p>


<h2>Buffer</h2>

<p>Buffers the data to write in RAM, periodically flushing it to another table. During the read operation, data is read from the buffer and the other table simultaneously.</p>

<pre class='text-example'>Buffer(database, table, num_layers, min_time, max_time, min_rows, max_rows, min_bytes, max_bytes)</pre>

<p>Engine parameters:
database, table - The table to flush data to. Instead of the database name, you can use a constant expression that returns a string.
num_layers - The level of parallelism. Physically, the table will be represented as &#39;num_layers&#39; of independent buffers. The recommended value is 16.
min_time, max_time, min_rows, max_rows, min_bytes, and max_bytes are conditions for flushing data from the buffer.</p>

<p>Data is flushed from the buffer and written to the destination table if all the &#39;min&#39; conditions or at least one &#39;max&#39; condition are met.
min_time, max_time - Condition for the time in seconds from the moment of the first write to the buffer.
min_rows, max_rows - Condition for the number of rows in the buffer.
min_bytes, max_bytes - Condition for the number of bytes in the buffer.</p>

<p>During the write operation, data is inserted to a &#39;num_layers&#39; number of random buffers. Or, if the data part to insert is large enough (greater than &#39;max_rows&#39; or &#39;max_bytes&#39;), it is written directly to the destination table, omitting the buffer.</p>

<p>The conditions for flushing the data are calculated separately for each of the &#39;num_layers&#39; buffers. For example, if num_layers = 16 and max_bytes = 100000000, the maximum RAM consumption is 1.6 GB.</p>

<p>Example:</p>

<pre class='text-example'>CREATE TABLE merge.hits_buffer AS merge.hits ENGINE = Buffer(merge, hits, 16, 10, 100, 10000, 1000000, 10000000, 100000000)</pre>

<p>Creating a &#39;merge.hits_buffer&#39; table with the same structure as &#39;merge.hits&#39; and using the Buffer engine. When writing to this table, data is buffered in RAM and later written to the &#39;merge.hits&#39; table. 16 buffers are created. The data in each of them is flushed if either 100 seconds have passed, or one million rows have been written, or 100 MB of data have been written; or if simultaneously 10 seconds have passed and 10,000 rows and 10 MB of data have been written. For example, if just one row has been written, after 100 seconds it will be flushed, no matter what. But if many rows have been written, the data will be flushed sooner.</p>

<p>When the server is stopped, with DROP TABLE or DETACH TABLE, buffer data is also flushed to the destination table.</p>

<p>You can set empty strings in single quotation marks for the database and table name. This indicates the absence of a destination table. In this case, when the data flush conditions are reached, the buffer is simply cleared. This may be useful for keeping a window of data in memory.</p>

<p>When reading from a Buffer table, data is processed both from the buffer and from the destination table (if there is one).
Note that the Buffer tables does not support an index. In other words, data in the buffer is fully scanned, which might be slow for large buffers. (For data in a subordinate table, the index it supports will be used.)</p>

<p>If the set of columns in the Buffer table doesn&#39;t match the set of columns in a subordinate table, a subset of columns that exist in both tables is inserted.</p>

<p>If the types don&#39;t match for one of the columns in the Buffer table and a subordinate table, an error message is entered in the server log and the buffer is cleared.
The same thing happens if the subordinate table doesn&#39;t exist when the buffer is flushed.</p>

<p>If you need to run ALTER for a subordinate table and the Buffer table, we recommend first deleting the Buffer table, running ALTER for the subordinate table, then creating the Buffer table again.</p>

<p>If the server is restarted abnormally, the data in the buffer is lost.</p>

<p>PREWHERE, FINAL and SAMPLE do not work correctly for Buffer tables. These conditions are passed to the destination table, but are not used for processing data in the buffer. Because of this, we recommend only using the Buffer table for writing, while reading from the destination table.</p>

<p>When adding data to a Buffer, one of the buffers is locked. This causes delays if a read operation is simultaneously being performed from the table.</p>

<p>Data that is inserted to a Buffer table may end up in the subordinate table in a different order and in different blocks. Because of this, a Buffer table is difficult to use for writing to a CollapsingMergeTree correctly. To avoid problems, you can set &#39;num_layers&#39; to 1.</p>

<p>If the destination table is replicated, some expected characteristics of replicated tables are lost when writing to a Buffer table. The random changes to the order of rows and sizes of data parts cause data deduplication to quit working, which means it is not possible to have a reliable &#39;exactly once&#39; write to replicated tables.</p>

<p>Due to these disadvantages, we can only recommend using a Buffer table in rare cases.</p>

<p>A Buffer table is used when too many INSERTs are received from a large number of servers over a unit of time and data can&#39;t be buffered before insertion, which means the INSERTs can&#39;t run fast enough.</p>

<p>Note that it doesn&#39;t make sense to insert data one row at a time, even for Buffer tables. This will only produce a speed of a few thousand rows per second, while inserting larger blocks of data can produce over a million rows per second (see the section &quot;Performance&quot;).</p>


<h2>Data replication</h2>

<h3>ReplicatedMergeTree</h3>
<h3>ReplicatedCollapsingMergeTree</h3>
<h3>ReplicatedAggregatingMergeTree</h3>
<h3>ReplicatedSummingMergeTree</h3>

<p>Replication is only supported for tables in the MergeTree family. Replication works at the level of an individual table, not the entire server. A server can store both replicated and non-replicated tables at the same time.</p>

<p>INSERT and ALTER are replicated (for more information, see ALTER). Compressed data is replicated, not query texts.
The CREATE, DROP, ATTACH, DETACH, and RENAME queries are not replicated. In other words, they belong to a single server. The CREATE TABLE query creates a new replicatable table on the server where the query is run. If this table already exists on other servers, it adds a new replica. The DROP TABLE query deletes the replica located on the server where the query is run. The RENAME query renames the table on one of the replicas. In other words, replicated tables can have different names on different replicas.</p>

<p>Replication is not related to sharding in any way. Replication works independently on each shard.</p>

<p>Replication is an optional feature. To use replication, set the addresses of the ZooKeeper cluster in the config file. Example:</p>

<pre class='text-example'>
&lt;zookeeper>
	&lt;node index=&quot;1&quot;>
		&lt;host>example1&lt;/host>
		&lt;port>2181&lt;/port>
	&lt;/node>
	&lt;node index=&quot;2&quot;>
		&lt;host>example2&lt;/host>
		&lt;port>2181&lt;/port>
	&lt;/node>
	&lt;node index=&quot;3&quot;>
		&lt;host>example3&lt;/host>
		&lt;port>2181&lt;/port>
	&lt;/node>
&lt;/zookeeper>
</pre>

<p>Use ZooKeeper version 3.4.5 or later. For example, the version in the Ubuntu Precise package is too old. You can get a newer version for Ubuntu Precise from the repository <a href='https://dist.yandex.net/metrika/stable/amd64/'>https://dist.yandex.net/metrika/stable/amd64/</a>.</p>

<p>You can specify any existing ZooKeeper cluster - the system will use a directory on it for its own data (the directory is specified when creating a replicatable table).</p>

<p>If ZooKeeper isn&#39;t set in the config file, you can&#39;t create replicated tables, and any existing replicated tables will be read-only.</p>

<p>ZooKeeper isn&#39;t used for SELECT queries. In other words, replication doesn&#39;t affect the productivity of SELECT queries - they work just as fast as for non-replicated tables.</p>

<p>For each INSERT query (more precisely, for each inserted block of data; the INSERT query contains a single block, or per block for every max_insert_block_size = 1048576 rows), approximately ten entries are made in ZooKeeper in several transactions. This leads to slightly longer latencies for INSERT compared to non-replicated tables. But if you follow the recommendations to insert data in batches of no more than one INSERT per second, it doesn&#39;t create any problems. The entire ClickHouse cluster used for coordinating one ZooKeeper cluster has a total of several hundred INSERTs per second. The throughput on data inserts (the number of rows per second) is just as high as for non-replicated data.</p>

<p>For very large clusters, you can use different ZooKeeper clusters for different shards. However, this hasn&#39;t proven necessary on the Yandex.Metrica cluster (approximately 300 servers).</p>

<p>Replication is asynchronous and multi-master. INSERT queries (as well as ALTER) can be sent to any available server. Data is inserted on this server, then sent to the other servers. Because it is asynchronous, recently inserted data appears on the other replicas with some latency. If part of the replicas are not available, the data on them is written when they become available. If a replica is available, the latency is the amount of time it takes to transfer the block of compressed data over the network.</p>

<p>There are no quorum writes. You can&#39;t write data with confirmation that it was received by more than one replica. If you write a batch of data to one replica and the server with this data ceases to exist before the data has time to get to the other replicas, this data will be lost.</p>

<p>Each block of data is written atomically. The INSERT query is divided into blocks up to max_insert_block_size = 1048576 rows. In other words, if the INSERT query has less than 1048576 rows, it is made atomically.</p>

<p>Blocks of data are duplicated. For multiple writes of the same data block (data blocks of the same size containing the same rows in the same order), the block is only written once. The reason for this is in case of network failures when the client application doesn&#39;t know if the data was written to the DB, so the INSERT query can simply be repeated. It doesn&#39;t matter which replica INSERTs were sent to with identical data - INSERTs are idempotent. This only works for the last 100 blocks inserted in a table.</p>

<p>During replication, only the source data to insert is transferred over the network. Further data transformation (merging) is coordinated and performed on all the replicas in the same way. This minimizes network usage, which means that replication works well when replicas reside in different datacenters. (Note that duplicating data in different datacenters is the main goal of replication.)</p>

<p>You can have any number of replicas of the same data. Yandex.Metrica uses double replication in production. Each server uses RAID-5 or RAID-6, and RAID-10 in some cases. This is a relatively reliable and convenient solution.</p>

<p>The system monitors data synchronicity on replicas and is able to recover after a failure. Failover is automatic (for small differences in data) or semi-automatic (when data differs too much, which may indicate a configuration error).</p>


<h3>Creating replicated tables</h3>

<p>The &#39;Replicated&#39; prefix is added to the table engine name. For example, ReplicatedMergeTree.</p>

<p>Two parameters are also added in the beginning of the parameters list - the path to the table in ZooKeeper, and the replica name in ZooKeeper.</p>

<p>Example:
<span class='text-example'>ReplicatedMergeTree(<b>&#39;/clickhouse/tables/{layer}-{shard}/hits&#39;</b>, <b>&#39;{replica}&#39;</b>, EventDate, intHash32(UserID), (CounterID, EventDate, intHash32(UserID), EventTime), 8192)</span></p>

<p>As the example shows, these parameters can contain substitutions in curly brackets. The substituted values are taken from the &#39;macros&#39; section of the config file. Example:</p>

<pre class='text-example'>
&lt;macros>
	&lt;layer>05&lt;/layer>
	&lt;shard>02&lt;/shard>
	&lt;replica>example05-02-1.yandex.ru&lt;/replica>
&lt;/macros>
</pre>

<p>The path to the table in ZooKeeper should be unique for each replicated table. Tables on different shards should have different paths.
In this case, the path consists of the following parts:</p>

<p><span class='inline-example'>/clickhouse/tables/</span> is the common prefix. We recommend using exactly this one.</p>

<p><span class='inline-example'>{layer}-{shard}</span> is the shard identifier. In this example it consists of two parts, since the Yandex.Metrica cluster uses bi-level sharding. For most tasks, you can leave just the {shard} substitution, which will be expanded to the shard identifier.</p>

<p><span class='inline-example'>hits</span> is the name of the node for the table in ZooKeeper. It is a good idea to make it the same as the table name. It is defined explicitly, because in contrast to the table name, it doesn&#39;t change after a RENAME query.</p>

<p>The replica name identifies different replicas of the same table. You can use the server name for this, as in the example. The name only needs to be unique within each shard.</p>

<p>You can define everything explicitly instead of using substitutions. This might be convenient for testing and for configuring small clusters, but it is inconvenient when working with large clusters.</p>

<p>Run CREATE TABLE on each replica. This query creates a new replicated table, or adds a new replica to an existing one.</p>

<p>If you add a new replica after the table already contains some data on other replicas, the data will be copied from the other replicas to the new one after running the query. In other words, the new replica syncs itself with the others.</p>

<p>To delete a replica, run DROP TABLE. However, only one replica is deleted - the one that resides on the server where you run the query.</p>


<h3>Recovery after failures</h3>

<p>If ZooKeeper is unavailable when a server starts, replicated tables switch to read-only mode. The system periodically attempts to connect to ZooKeeper.</p>

<p>If ZooKeeper is unavailable during an INSERT, or an error occurs when interacting with ZooKeeper, an exception is thrown.</p>

<p>After connecting to ZooKeeper, the system checks whether the set of data in the local file system matches the expected set of data (ZooKeeper stores this information). If there are minor inconsistencies, the system resolves them by syncing data with the replicas.</p>

<p>If the system detects broken data parts (with the wrong size of files) or unrecognized parts (parts written to the file system but not recorded in ZooKeeper), it moves them to the &#39;detached&#39; subdirectory (they are not deleted). Any missing parts are copied from the replicas.</p>

<p>Note that ClickHouse does not perform any destructive actions such as automatically deleting a large amount of data.</p>

<p>When the server starts (or establishes a new session with ZooKeeper), it only checks the quantity and sizes of all files. If the file sizes match but bytes have been changed somewhere in the middle, this is not detected immediately, but only when attempting to read the data for a SELECT query. The query throws an exception about a non-matching checksum or size of a compressed block. In this case, data parts are added to the verification queue and copied from the replicas if necessary.</p>

<p>If the local set of data differs too much from the expected one, a safety mechanism is triggered. The server enters this in the log and refuses to launch. The reason for this is that this case may indicate a configuration error, such as if a replica on a shard was accidentally configured like a replica on a different shard. However, the thresholds for this mechanism are set fairly low, and this situation might occur during normal failure recovery. In this case, data is restored semi-automatically - by &quot;pushing a button&quot;.</p>

<p>To start recovery, create the node <span class='inline-example'>/<i>path_to_table</i>/<i>replica_name</i>/flags/force_restore_data</span>  in ZooKeeper with any content, and launch the server. On start, the server deletes this flag and starts recovery.</p>


<h3>Recovery after complete data loss</h3>

<p>If all data and metadata disappeared from one of the servers, follow these steps for recovery:</p>

<p>1. Install ClickHouse on the server. Define substitutions correctly in the config file that contains the shard identifier and replicas, if you use them.</p>

<p>2. If you had unreplicated tables that must be manually duplicated on the servers, copy their data from a replica (in the directory <span class='inline-example'>/opt/clickhouse/data/<i>db_name</i>/<i>table_name</i>/</span>). If replicated tables had unreplicated parts, synchronize them as well. Note that these exist only if you migrated from MergeTree to ReplicatedMergeTree (see &quot;Converting from MergeTree to ReplicatedMergeTree&quot;).</p>

<p>3. Copy table definitions located in <span class='inline-example'>/opt/clickhouse/metadata/</span> from a replica. If a shard or replica identifier is defined explicitly in the table definitions, correct it so that it corresponds to this replica. (Alternatively, launch the server and make all the ATTACH TABLE queries that should have been in the .sql files in <span class='inline-example'>/opt/clickhouse/metadata/</span>.)</p>

<p>4. Create the <span class='inline-example'>/<i>path_to_table</i>/<i>replica_name</i>/flags/force_restore_data</span> node in ZooKeeper with any content, and launch the server (restart it if it is already running). Data will be downloaded from replicas.</p>

<p>An alternative recovery option is to delete information about the lost replica from ZooKeeper ( <span class='inline-example'>/<i>path_to_table</i>/<i>replica_name</i></span>), then create the replica again as described in &quot;Creating replicated tables&quot;.</p>

<p>There is no restriction on network bandwidth during recovery. Keep this in mind if you are restoring many replicas at once.</p>


<h3>Converting from MergeTree to ReplicatedMergeTree</h3>

<p>From here on, we use &quot;MergeTree&quot; to refer to all the table engines in the MergeTree family, including ReplicatedMergeTree.</p>

<p>If you had a MergeTree table that was manually replicated, you can convert it to a replicatable table. You might need to do this if you have already collected a large amount of data in a MergeTree table and now you want to enable replication.</p>

<p>There are two ways to do this:</p>

<p>1. Leave the old data &quot;as is&quot; without syncing it.</p>

<p>To do this, rename the existing MergeTree table, then create a ReplicatedMergeTree table with the old name.
In the directory with data for the new table (<span class='inline-example'>/opt/clickhouse/data/<i>db_name</i>/<i>table_name</i>/</span>), create the &#39;unreplicated&#39; subdirectory and move the data from the old table to it. Then restart the server.</p>

<p>For read requests, the replicated table will also read from the &#39;unreplicated&#39; data set. The integrity of this data is not monitored in any way.</p>

<p>2. Add the old data to the set of replicatable data.</p>

<p>If the data differs on various replicas, first sync it, or delete this data on all the replicas except one.</p>

<p>Rename the existing MergeTree table, then create a ReplicatedMergeTree table with the old name.
Move the data from the old table to the &#39;detached&#39; subdirectory inside the directory with the new table data (<span class='inline-example'>/opt/clickhouse/data/<i>db_name</i>/<i>table_name</i>/</span>).
Then run ALTER TABLE ATTACH PART on one of the replicas to add these data parts to the working set.</p>

<p>If exactly the same parts exist on the other replicas, they are added to the working set on them. If not, the parts are downloaded from the replica that has them.</p>


<h3>Converting from ReplicatedMergeTree to MergeTree</h3>

<p>Create a MergeTree table with a different name. Move all the data from the directory with the ReplicatedMergeTree table data to the new table&#39;s data directory. Then delete the ReplicatedMergeTree table and restart the server.</p>

<p>If you want to get rid of a ReplicatedMergeTree table without launching the server:
- Delete the corresponding .sql file in the metadata directory (<span class='inline-example'>/opt/clickhouse/metadata/</span>).
- Delete the corresponding path in ZooKeeper (<span class='inline-example'>/<i>path_to_table</i>/<i>replica_name</i></span>).
After this, you can launch the server, create a MergeTree table, move the data to its directory, and then restart the server.</p>


<h3>Recovery when metadata in the ZooKeeper cluster is lost or damaged</h3>

<p>If you lost ZooKeeper, you can save data by moving it to an unreplicated table as described above.</p>



</div>
<div class='island'>
<h1>System tables</h1>
</div>
<div class='island'>

<p>System tables are used for implementing part of the system&#39;s functionality, and for providing access to information about how the system is working.
You can&#39;t delete a system table (but you can perform DETACH).
System tables don&#39;t have files with data on the disk or files with metadata. The server creates all the system tables when it starts.
System tables are read-only.
System tables are located in the &#39;system&#39; database.</p>

<h2>system.one</h2>

<p>This table contains a single row with a single &#39;dummy&#39; UInt8 column containing the value 0.
This table is used if a SELECT query doesn&#39;t specify the FROM clause.
This is similar to the DUAL table found in other DBMSs.</p>

<h2>system.numbers</h2>

<p>This table contains a single UInt64 column named &#39;number&#39; that contains almost all the natural numbers starting from zero.
You can use this table for tests, or if you need to do a brute force search.
Reads from this table are not parallelized.</p>

<h2>system.numbers_mt</h2>

<p>The same as &#39;system.numbers&#39; but reads are parallelized. The numbers can be returned in any order.
Used for tests.</p>

<h2>system.tables</h2>

<p>This table contains the String columns &#39;database&#39;, &#39;name&#39;, and &#39;engine&#39;.
Each table that the server knows about is entered in the &#39;system.tables&#39; table.
There is an issue: table engines are specified without parameters.
This system table is used for implementing SHOW TABLES queries.</p>

<h2>system.databases</h2>

<p>This table contains a single String column called &#39;name&#39; - the name of a database.
Each database that the server knows about has a corresponding entry in the table.
This system table is used for implementing the SHOW DATABASES query.</p>

<h2>system.processes</h2>

<p>This system table is used for implementing the SHOW PROCESSLIST query.
Columns:
<pre class='text-example'>
user String              - Name of the user who made the request. For distributed query processing, this is the user who helped the requestor server send the query to this server, not the user who made the distributed request on the requestor server.

address String           - The IP address the request was made from. The same for distributed processing.

elapsed Float64          - The time in seconds since request execution started.

rows_read UInt64         - The number of rows read from the table. For distributed processing, on the requestor server, this is the total for all remote servers.

bytes_read UInt64        - The number of uncompressed bytes read from the table. For distributed processing, on the requestor server, this is the total for all remote servers.

total_rows_approx UInt64 - The approximation of the total number of rows that should be read. For distributed processing, on the requestor server, this is the total for all remote servers. It can be updated during request processing, when new sources to process become known.

memory_usage UInt64      - How much memory the request uses. It might not include some types of dedicated memory.

query String             - The query text. For INSERT, it doesn&#39;t include the data to insert.

query_id String          - Query ID, if defined.</p>
</pre>

<h2>system.events</h2>

<p>Contains information about the number of events that have occurred in the system. This is used for profiling and monitoring purposes.
Example: The number of processed SELECT queries.
Columns: &#39;event String&#39; - the event name, and &#39;value UInt64&#39; - the quantity.</p>

<h2>system.clusters</h2>

<p>Contains information about clusters available in the config file and the servers in them.
Columns:</p>

<pre class='text-example'>
cluster String      - Cluster name.
shard_num UInt32    - Number of a shard in the cluster, starting from 1.
shard_weight UInt32 - Relative weight of a shard when writing data.
replica_num UInt32  - Number of a replica in the shard, starting from 1.
host_name String    - Host name as specified in the config.
host_address String - Host&#39;s IP address obtained from DNS.
port UInt16         - The port used to access the server.
user String         - The username to use for connecting to the server.
</pre>

<h2>system.columns</h2>

<p>Contains information about the columns in all tables.
You can use this table to get information similar to DESCRIBE TABLE, but for multiple tables at once.</p>

<pre class='text-example'>
database String           - Name of the database the table is located in.
table String              - Table name.
name String               - Column name.
type String               - Column type.
default_type String       - Expression type (DEFAULT, MATERIALIZED, ALIAS) for the default value, or an empty string if it is not defined.
default_expression String - Expression for the default value, or an empty string if it is not defined.
</pre>

<h2>system.dictionaries</h2>

<p>Contains information about external dictionaries.
Columns:</p>

<pre class='text-example'>
name String                   - Dictionary name.
type String                   - Dictionary type: Flat, Hashed, Cache.
origin String                 - Path to the config file where the dictionary is described.
attribute.names Array(String) - Array of attribute names provided by the dictionary.
attribute.types Array(String) - Corresponding array of attribute types provided by the dictionary.
has_hierarchy UInt8           - Whether the dictionary is hierarchical.
bytes_allocated UInt64        - The amount of RAM used by the dictionary.
hit_rate Float64              - For cache dictionaries, the percent of usage for which the value was in the cache.
element_count UInt64          - The number of items stored in the dictionary.
load_factor Float64           - The filled percentage of the dictionary (for a hashed dictionary, it is the filled percentage of the hash table).
creation_time DateTime        - Time spent for the creation or last successful reload of the dictionary.
last_exception String         - Text of an error that occurred when creating or reloading the dictionary, if the dictionary couldn&#39;t be created.
source String                 - Text describing the data source for the dictionary.
</pre>

<p>Note that the amount of memory used by the dictionary is not proportional to the number of items stored in it. So for flat and cached dictionaries, all the memory cells are pre-assigned, regardless of how full the dictionary actually is.</p>


<h2>system.functions</h2>

<p>Contains information about normal and aggregate functions.
Columns:</p>

<pre class='text-example'>
name String           - Function name.
is_aggregate UInt8    - Whether it is an aggregate function.
</pre>

<h2>system.merges</h2>

<p>Contains information about merges currently in process for tables in the MergeTree family.
Columns:</p>

<pre class='text-example'>
database String                    - Name of the database the table is located in.
table String                       - Name of the table.
elapsed Float64                    - Time in seconds since the merge started.
progress Float64                   - Percent of progress made, from 0 to 1.
num_parts UInt64                   - Number of parts to merge.
result_part_name String            - Name of the part that will be formed as the result of the merge.
total_size_bytes_compressed UInt64 - Total size of compressed data in the parts being merged.
total_size_marks UInt64            - Total number of marks in the parts being merged.
bytes_read_uncompressed UInt64     - Amount of bytes read, decompressed.
rows_read UInt64                   - Number of rows read.
bytes_written_uncompressed UInt64  - Amount of bytes written, uncompressed.
rows_written UInt64                - Number of rows written.
</pre>

<h2>system.parts</h2>

<p>Contains information about parts of a table in the MergeTree family.
Columns:</p>

<pre class='text-example'>
database String            - Name of the database where the table that this part belongs to is located.
table String               - Name of the table that this part belongs to.
engine String              - Name of the table engine, without parameters.
partition String           - Name of the partition, in the format YYYYMM.
name String                - Name of the part.
replicated UInt8           - Whether the part belongs to replicated data.
active UInt8               - Whether the part is used in a table, or is no longer needed and will be deleted soon. Inactive parts remain after merging.
marks UInt64               - Number of marks - multiply by the index granularity (usually 8192) to get the approximate number of rows in the part.
bytes UInt64               - Number of bytes when compressed.
modification_time DateTime - Time the directory with the part was modified. Usually corresponds to the part&#39;s creation time.
remove_time DateTime       - For inactive parts only - the time when the part became inactive.
refcount UInt32            - The number of places where the part is used. A value greater than 2 indicates that this part participates in queries or merges.
</pre>

<h2>system.replicas</h2>

<p>Contains information and status for replicated tables residing on the local server. This table can be used for monitoring. The table contains a row for every Replicated* table.</p>

<p>Example:</p>

<pre class='text-example'>
SELECT *
FROM system.replicas
WHERE table = &#39;visits&#39;
FORMAT Vertical

Row 1:
──────
database:           merge
table:              visits
engine:             ReplicatedCollapsingMergeTree
is_leader:          1
is_readonly:        0
is_session_expired: 0
future_parts:       1
parts_to_check:     0
zookeeper_path:     /clickhouse/tables/01-06/visits
replica_name:       example01-06-1.yandex.ru
replica_path:       /clickhouse/tables/01-06/visits/replicas/example01-06-1.yandex.ru
columns_version:    9
queue_size:         1
inserts_in_queue:   0
merges_in_queue:    1
log_max_index:      596273
log_pointer:        596274
total_replicas:     2
active_replicas:    2
</pre>

<p>Columns:</p>

<pre class='text-example'>
database:          Database name.
table:              Table name.
engine:             Table engine name.

is_leader:          Whether the replica is the leader.
Only one replica can be the leader at a time. The leader is responsible for selecting background merges to perform.
Note that writes can be performed to any replica that is available and has a session in ZK, regardless of whether it is a leader.

is_readonly:        Whether the replica is in read-only mode.
This mode is turned on if the config doesn&#39;t have sections with ZK, if an unknown error occurred when reinitializing sessions in ZK, and during session reinitialization in ZK.

is_session_expired: Whether the session with ZK has expired.
Basically the same as &#39;is_readonly&#39;.

future_parts:       The number of data parts that will appear as the result of INSERTs or merges that haven&#39;t been done yet.

parts_to_check:     The number of data parts in the queue for verification.
A part is put in the verification queue if there is suspicion that it might be damaged.

zookeeper_path:     Path to table data in ZK.
replica_name:       Replica name in ZK. Different replicas of the same table have different names.
replica_path:      Path to replica data in ZK. The same as concatenating &#39;zookeeper_path/replicas/replica_path&#39;.

columns_version:    Version number of the table structure. Indicates how many times ALTER was performed. If replicas have different versions, it means some replicas haven&#39;t made all of the ALTERs yet.

queue_size:         Size of the queue for operations waiting to be performed. Operations include inserting blocks of data, merges, and certain other actions. It usually coincides with &#39;future_parts&#39;.

inserts_in_queue:   Number of inserts of blocks of data that need to be made. Insertions are usually replicated fairly quickly. If this number is large, it means something is wrong.

merges_in_queue:    The number of merges waiting to be made. Sometimes merges are lengthy, so this value may be greater than one for a long time.

The next 4 columns have a non-zero value only where there is an active session with ZK.

log_max_index:      Maximum entry number in the log of general activity.
log_pointer:        Maximum entry number from the log of general activity that the replica copied to its queue for execution, plus one.
If log_pointer is much smaller than log_max_index, something is wrong.

total_replicas:     The total number of known replicas of this table.
active_replicas:    The number of replicas of this table that have a session in ZK (i.e., the number of functioning replicas).
</pre>

<p>If you request all the columns, the table may work a bit slowly, since several reads from ZK are made for each row.
If you don&#39;t request the last 4 columns (log_max_index, log_pointer, total_replicas, active_replicas), the table works quickly.</p>

<p>For example, you can check that everything is working correctly like this:</p>

<pre class='text-example'>
SELECT
    database,
    table,
    is_leader,
    is_readonly,
    is_session_expired,
    future_parts,
    parts_to_check,
    columns_version,
    queue_size,
    inserts_in_queue,
    merges_in_queue,
    log_max_index,
    log_pointer,
    total_replicas,
    active_replicas
FROM system.replicas
WHERE
       is_readonly
    OR is_session_expired
    OR future_parts > 20
    OR parts_to_check > 10
    OR queue_size > 20
    OR inserts_in_queue > 10
    OR log_max_index - log_pointer > 10
    OR total_replicas &lt; 2
    OR active_replicas &lt; total_replicas
</pre>

<p>If this query doesn&#39;t return anything, it means that everything is fine.</p>

<h2>system.settings</h2>

<p>Contains information about settings that are currently in use (i.e. used for executing the query you are using to read from the system.settings table).</p>

<p>Columns:</p>

<pre class='text-example'>
name String   - Setting name.
value String  - Setting value.
changed UInt8 - Whether the setting was explicitly defined in the config or explicitly changed.
</pre>

<p>Example:</p>

<pre class='text-example'>
SELECT *
FROM system.settings
WHERE changed

┌─name───────────────────┬─value───────┬─changed─┐
│ max_threads            │ 8           │       1 │
│ use_uncompressed_cache │ 0           │       1 │
│ load_balancing         │ random      │       1 │
│ max_memory_usage       │ 10000000000 │       1 │
└────────────────────────┴─────────────┴─────────┘
</pre>


<h2>system.zookeeper</h2>

<p>Allows reading data from the ZooKeeper cluster defined in the config.
The query must have a &#39;path&#39; equality condition in the WHERE clause. This is the path in ZooKeeper for the children that you want to get data for.</p>

<p>Query SELECT * FROM system.zookeeper WHERE path = &#39;/clickhouse&#39; outputs data for all children on the /clickhouse node.
To output data for all root nodes, write path = &#39;/&#39;.
If the path specified in &#39;path&#39; doesn&#39;t exist, an exception will be thrown.</p>

<p>Columns:</p>

<pre class='text-example'>
name String          - Name of the node.
path String          - Path to the node.
value String         - Value of the node.
dataLength Int32     - Size of the value.
numChildren Int32    - Number of children.
czxid Int64          - ID of the transaction that created the node.
mzxid Int64          - ID of the transaction that last changed the node.
pzxid Int64          - ID of the transaction that last added or removed children.
ctime DateTime       - Time of node creation.
mtime DateTime       - Time of the last node modification.
version Int32        - Node version - the number of times the node was changed.
cversion Int32       - Number of added or removed children.
aversion Int32       - Number of changes to ACL.
ephemeralOwner Int64 - For ephemeral nodes, the ID of the session that owns this node.
</pre>

<p>Example:</p>

<pre class='text-example'>
SELECT *
FROM system.zookeeper
WHERE path = &#39;/clickhouse/tables/01-08/visits/replicas&#39;
FORMAT Vertical

Row 1:
──────
name:           example01-08-1.yandex.ru
value:
czxid:          932998691229
mzxid:          932998691229
ctime:          2015-03-27 16:49:51
mtime:          2015-03-27 16:49:51
version:        0
cversion:       47
aversion:       0
ephemeralOwner: 0
dataLength:     0
numChildren:    7
pzxid:          987021031383
path:           /clickhouse/tables/01-08/visits/replicas

Row 2:
──────
name:           example01-08-2.yandex.ru
value:
czxid:          933002738135
mzxid:          933002738135
ctime:          2015-03-27 16:57:01
mtime:          2015-03-27 16:57:01
version:        0
cversion:       37
aversion:       0
ephemeralOwner: 0
dataLength:     0
numChildren:    7
pzxid:          987021252247
path:           /clickhouse/tables/01-08/visits/replicas
</pre>



</div>
<div class='island'>
<h1>Table functions</h1>
</div>
<div class='island'>

<p>Table functions can be specified in the FROM clause instead of the database and table names.
Table functions can only be used if &#39;readonly&#39; is not set.
Table functions aren&#39;t related to other functions.</p>

<h2>merge</h2>

<p><span class='inline-example'>merge(db_name, &#39;tables_regexp&#39;)</span> creates a temporary Merge table. For more information, see the section &quot;Table engines, Merge&quot;.
The table structure is taken from the first table encountered that matches the regular expression.</p>

<h2>remote</h2>

<p><span class='inline-example'>remote(&#39;addresses_expr&#39;, db, table[, &#39;user&#39;[, &#39;password&#39;]])</span>
or <span class='inline-example'>remote(&#39;addresses_expr&#39;, db.table[, &#39;user&#39;[, &#39;password&#39;]])</span>
- Allows accessing a remote server without creating a Distributed table.</p>

<p><span class='inline-example'>addresses_expr</span> - An expression that generates addresses of remote servers.</p>

<p>This may be just one server address. The server address is host:port, or just the host. The host can be specified as the server name, or as the IPv4 or IPv6 address. An IPv6 address is specified in square brackets. The port is the TCP port on the remote server. If the port is omitted, it uses <span class='inline-example'>tcp_port</span> from the server&#39;s config file (by default, 9000).</p>

<p>Note: As an exception, when specifying an IPv6 address, the port is required.</p>

<p>Examples:</p>
<pre class='text-example'>
example01-01-1
example01-01-1:9000
localhost
127.0.0.1
[::]:9000
[2a02:6b8:0:1111::11]:9000</pre>

<p>Multiple addresses can be comma-separated. In this case, the query goes to all the specified addresses (like to shards with different data) and uses distributed processing.</p>

<p>Example:</p>
<pre class='text-example'>example01-01-1,example01-02-1</pre>

<p>Part of the expression can be specified in curly brackets. The previous example can be written as follows:</p>
<pre class='text-example'>example01-0{1,2}-1</pre>

<p>Curly brackets can contain a range of numbers separated by two dots (non-negative integers). In this case, the range is expanded to a set of values that generate shard addresses. If the first number starts with zero, the values are formed with the same zero alignment.
The previous example can be written as follows:</p>
<pre class='text-example'>example01-{01..02}-1</pre>

<p>If you have multiple pairs of curly brackets, it generates the direct product of the corresponding sets.</p>

3623
<p>Addresses and fragments in curly brackets can be separated by the pipe (|) symbol. In this case, the corresponding sets of addresses are interpreted as replicas, and the query will be sent to the first healthy replica. The replicas are evaluated in the order currently set in the &#39;load_balancing&#39; setting.
3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744
Example:</p>

<pre class='text-example'>example01-{01..02}-{1|2}</pre>

<p>This example specifies two shards that each have two replicas.</p>

<p>The number of addresses generated is limited by a constant. Right now this is 1000 addresses.</p>

<p>Using the &#39;remote&#39; table function is less optimal than creating a Distributed table, because in this case, the server connection is re-established for every request. In addition, if host names are set, the names are resolved, and errors are not counted when working with various replicas. When processing a large number of queries, always create the Distributed table ahead of time, and don&#39;t use the &#39;remote&#39; table function.</p>

<p>The &#39;remote&#39; table function can be useful in the following cases:
- Accessing a specific server for data comparison, debugging, and testing.
- Queries between various ClickHouse clusters for research purposes.
- Infrequent distributed requests that are made manually.
- Distributed requests where the set of servers is re-defined each time.</p>

<p>The username can be omitted. In this case, the &#39;default&#39; username is used.
The password can be omitted. In this case, an empty password is used.</p>

</div>
<div class='island'>
<h1>Formats</h1>
</div>
<div class='island'>

<p>The format determines how data is given to you after SELECTs, and how it is accepted for INSERTs.</p>


<h2>Native</h2>

<p>The most efficient format. Data is written and read by blocks in binary format. For each block, the number of rows, number of columns, column names and types, and parts of columns in this block are recorded one after another. In other words, this format is &quot;columnar&quot; - it doesn&#39;t convert columns to rows. This is the format used in the native interface for interaction between servers, for using the command-line client, and for C++ clients.</p>

<p>You can use this format to quickly generate dumps that can only be read by the ClickHouse DBMS. It doesn&#39;t make sense to work with this format yourself.</p>


<h2>TabSeparated</h2>

<p>In TabSeparated format, data is written by row. Each row contains values separated by tabs. Each value is follow by a tab, except the last value in the row, which is followed by a line break. Strictly Unix line breaks are assumed everywhere. The last row also must contain a line break at the end. Values are written in text format, without enclosing quotation marks, and with special characters escaped.</p>

<p>Whole numbers are written in decimal form. Numbers may contain an extra &quot;+&quot; symbol at the beginning (but it is not recorded during a write). Non-negative numbers can&#39;t contain the negative sign. When reading, it is allowed to parse an empty string as a zero, or (for signed types) a string consisting of just a minus sign as a zero. Numbers that do not fit into the corresponding data type may be parsed as a different number, without an error message.</p>

<p>Floating-point numbers are written in decimal form. The dot is used as the decimal separator. Exponential entries are supported, as are &#39;inf&#39;, &#39;+inf&#39;, &#39;-inf&#39;, and &#39;nan&#39;. An entry of floating-point numbers may begin or end with a decimal point.
For writes, accuracy may be lost on floating-point numbers.
For reads, a result is not necessarily the nearest machine-representable number.</p>

<p>Data is written in YYYY-MM-DD format and read in the same format, but with any characters as separators.
Dates with times are written in the format YYYY-MM-DD hh:mm:ss and read in the same format, but with any characters as separators.
This all occurs in the system time zone at the time the client or server starts (depending on which one formats data). For dates with times, daylight saving time is not specified. So if a dump has times during daylight saving time, the dump does not unequivocally match the data, and a read will select one of the two times.
During a read operation, incorrect dates and dates with times can be parsed with natural overflow or as null dates and times, without an error message.</p>

<p>As an exception, reading dates with times is also supported in Unix timestamp format, if it consists of exactly 10 decimal digits. However, the result is not time zone-dependent. The formats YYYY-MM-DD hh:mm:ss and NNNNNNNNNN are differentiated automatically.</p>

<p>Strings are written with backslash-escaped special characters. The following escape sequences are used: <span class='inline-example'>\b</span>, <span class='inline-example'>\f</span>, <span class='inline-example'>\r,</span> <span class='inline-example'>\n</span>, <span class='inline-example'>\t</span>, <span class='inline-example'>\0</span>, <span class='inline-example'>\&#39;</span>, and <span class='inline-example'>\\</span>. For a read, any sequences of the type <span class='inline-example'>\<i>x</i></span> are also supported, where <i>x</i> is any character. These sequences are converted to <i>x</i>. This means that a read supports formats where a line break can be written as <span class='inline-example'>\n</span> or as <span class='inline-example'>\</span> and a line break. For example, the string &#39;Hello world&#39; with a line break between the words instead of a space can be retrieved in any of the following variations:</p>

<pre class='text-example'>Hello\nworld</pre>

<pre class='text-example'>Hello\
world</pre>

<p>The second variant is supported because MySQL uses it when writing tab-separated dumps.</p>

<p>Only a small set of symbols are escaped. You can easily stumble onto a string value that your terminal will ruin in output.</p>

<p>Arrays are written as a list of comma-separated values in square brackets. Number items in the array are written as normally, but dates, dates with times, and strings are written in single quotes with the same escaping rules as above.</p>

<p>The TabSeparated format is convenient for processing data using custom programs and scripts. It is used by default in the HTTP interface, and in the command-line client&#39;s batch mode. This format also allows transferring data between different DBMSs. For example, you can get a dump from MySQL and upload it to ClickHouse, or vice versa.</p>

<p>The TabSeparated format supports outputting total values (when using WITH TOTALS) and extreme values (when &#39;extremes&#39; is set to 1). In these cases, the total values and extremes are output after the main data. The main result, total values, and extremes are separated from each other by an empty line. Example:</p>

<pre class='text-example'>SELECT EventDate, count() AS c FROM test.hits GROUP BY EventDate WITH TOTALS ORDER BY EventDate FORMAT TabSeparated</pre>

<pre class='text-example'>
2014-03-17      1406958
2014-03-18      1383658
2014-03-19      1405797
2014-03-20      1353623
2014-03-21      1245779
2014-03-22      1031592
2014-03-23      1046491

0000-00-00      8873898

2014-03-17      1031592
2014-03-23      1406958
</pre>

<h2>TabSeparatedWithNames</h2>

<p>Differs from the TabSeparated format in that the column names are written in the first row.
For a read, the first row is completely ignored. You can&#39;t use column names to determine their position or to check their correctness.</p>


<h2>TabSeparatedWithNamesAndTypes</h2>

<p>Differs from the TabSeparated format in that the column names are written to the first row, while the column types are in the second row.
For a read, the first and second rows are completely ignored.</p>


<h2>TabSeparatedRaw</h2>

<p>Differs from the TabSeparated format in that the rows are written without escaping.
This format is only appropriate for writing (outputting a query result), but not for reading (retrieving data to insert in a table).</p>


<h2>BlockTabSeparated</h2>

<p>Data is not written by row, but by column and block.
Each block consists of parts of columns, each of which is written on a separate line.
The values are tab-separated. The last value in a column part is followed by a line break instead of a tab.
Blocks are separated by a double line break.
The rest of the rules are the same as in the TabSeparated format.
This format is only appropriate for writes, not for reads.</p>


<h2>RowBinary</h2>

<p>Writes data by row in binary format. Rows and values are listed consecutively, without separators.
This format is less efficient than the Native format, since it is row-based.</p>


<h2>Pretty</h2>

<p>Writes data as Unicode-art tables, also using ANSI-escape sequences for setting colors in the terminal.
A full grid of the table is drawn, and each row occupies two lines in the terminal. Each result block is output as a separate table. This is necessary so that blocks can be output without buffering results (buffering would be necessary in order to pre-calculate the visible width of all the values).
To avoid dumping too much data to the terminal, only the first 10,000 rows are printed. If the number of rows is greater than or equal to 10,000, the message &quot;Showed first 10,000&quot; is printed.
This format is only appropriate for writes (outputting a query result), but not for reads.</p>

<p>The Pretty format supports outputting total values (when using WITH TOTALS) and extremes (when &#39;extremes&#39; is set to 1). In these cases, total values and extreme values are output after the main data, in separate tables. Example (shown for the PrettyCompact format):</p>

<pre class='text-example'>SELECT EventDate, count() AS c FROM test.hits GROUP BY EventDate WITH TOTALS ORDER BY EventDate FORMAT PrettyCompact</pre>

<pre class='text-example'>
┌──EventDate─┬───────c─┐
│ 2014-03-17 │ 1406958 │
│ 2014-03-18 │ 1383658 │
│ 2014-03-19 │ 1405797 │
│ 2014-03-20 │ 1353623 │
│ 2014-03-21 │ 1245779 │
│ 2014-03-22 │ 1031592 │
│ 2014-03-23 │ 1046491 │
└────────────┴─────────┘

Totals:
┌──EventDate─┬───────c─┐
│ 0000-00-00 │ 8873898 │
└────────────┴─────────┘

Extremes:
┌──EventDate─┬───────c─┐
│ 2014-03-17 │ 1031592 │
│ 2014-03-23 │ 1406958 │
└────────────┴─────────┘
</pre>

<h2>PrettyCompact</h2>

<p>Differs from Pretty in that the grid is drawn between rows and the result is more compact. This format is used by default in the command-line client in interactive mode.</p>


<h2>PrettyCompactMonoBlock</h2>

<p>Differs from PrettyCompact in that up to 10,000 rows are buffered, then output as a single table, not by blocks.</p>


<h2>PrettySpace</h2>

<p>Differs from PrettyCompact in that whitespace (space characters) is used instead of the grid.</p>


<h2>PrettyNoEscapes</h2>

<p>Differs from Pretty in that ANSI-escape sequences aren&#39;t used. This is necessary for displaying this format in a browser, as well as for using the &#39;watch&#39; command-line utility.
Example:</p>

<pre class='text-example'>watch -n1 &quot;clickhouse-client --query=&#39;SELECT * FROM system.events FORMAT PrettyCompactNoEscapes&#39;&quot;</pre>

<p>You can use the HTTP interface for displaying in the browser.</p>


<h2>PrettyCompactNoEscapes</h2>

<p>The same.</p>


<h2>PrettySpaceNoEscapes</h2>

<p>The same.</p>


<h2>Vertical</h2>

<p>Prints each value on a separate line with the column name specified. This format is convenient for printing just one or a few rows, if each row consists of a large number of columns.
This format is only appropriate for writes, not for reads.</p>


<h2>Values</h2>

<p>Prints every row in brackets. Rows are separated by commas. There is no comma after the last row. The values inside the brackets are also comma-separated. Numbers are output in decimal format without quotes. Arrays are output in square brackets. Strings, dates, and dates with times are output in quotes. Escaping rules and parsing are similar to the TabSeparated format. During formatting, extra spaces aren&#39;t inserted, but during parsing, they are allowed and skipped (except for spaces inside array values, which are not allowed).</p>

<p>This is the format that is used in INSERT INTO t VALUES ...
But you can also use it for output.</p>


<h2>JSON</h2>

<p>Outputs data in JSON format. Besides data tables, it also outputs column names and types, along with some additional information - the total number of output rows, and the number of rows that could have been output if there weren&#39;t a LIMIT. Example:</p>

<pre class='text-example'>SELECT SearchPhrase, count() AS c FROM test.hits GROUP BY SearchPhrase WITH TOTALS ORDER BY c DESC LIMIT 5 FORMAT JSON</pre>

<pre class='text-example'>
{
        &quot;meta&quot;:
        [
                {
                        &quot;name&quot;: &quot;SearchPhrase&quot;,
                        &quot;type&quot;: &quot;String&quot;
                },
                {
                        &quot;name&quot;: &quot;c&quot;,
                        &quot;type&quot;: &quot;UInt64&quot;
                }
        ],

        &quot;data&quot;:
        [
                {
                        &quot;SearchPhrase&quot;: &quot;&quot;,
                        &quot;c&quot;: &quot;8267016&quot;
                },
                {
                        &quot;SearchPhrase&quot;: &quot;bath interiors&quot;,
                        &quot;c&quot;: &quot;2166&quot;
                },
                {
                        &quot;SearchPhrase&quot;: &quot;yandex&quot;,
                        &quot;c&quot;: &quot;1655&quot;
                },
                {
                        &quot;SearchPhrase&quot;: &quot;spring 2014 fashion&quot;,
                        &quot;c&quot;: &quot;1549&quot;
                },
                {
                        &quot;SearchPhrase&quot;: &quot;freeform photo&quot;,
                        &quot;c&quot;: &quot;1480&quot;
                }
        ],

        &quot;totals&quot;:
        {
                &quot;SearchPhrase&quot;: &quot;&quot;,
                &quot;c&quot;: &quot;8873898&quot;
        },

        &quot;extremes&quot;:
        {
                &quot;min&quot;:
                {
                        &quot;SearchPhrase&quot;: &quot;&quot;,
                        &quot;c&quot;: &quot;1480&quot;
                },
                &quot;max&quot;:
                {
                        &quot;SearchPhrase&quot;: &quot;&quot;,
                        &quot;c&quot;: &quot;8267016&quot;
                }
        },

        &quot;rows&quot;: 5,

        &quot;rows_before_limit_at_least&quot;: 141137
}
</pre>

<p>JSON is compatible with JavaScript. For this purpose, certain symbols are additionally escaped: the forward slash <span class='inline-example'>/</span> is escaped as <span class='inline-example'>\/</span>; alternative line breaks <span class='inline-example'>U+2028</span> and <span class='inline-example'>U+2029</span>, which don&#39;t work in some browsers, are escaped as <span class='inline-example'>\u<i>XXXX</i></span>-sequences. ASCII control characters are escaped: backspace, form feed, line feed, carriage return, and horizontal tab as <span class='inline-example'>\b</span>, <span class='inline-example'>\f</span>, <span class='inline-example'>\n</span>, <span class='inline-example'>\r</span>, and <span class='inline-example'>\t</span> respectively, along with the rest of the bytes from the range 00-1F using <span class='inline-example'>\u<i>XXXX</i></span>-sequences. Invalid UTF-8 sequences are changed to the replacement character <span class='inline-example'></span> and, thus, the output text will consist of valid UTF-8 sequences. UInt64 and Int64 numbers are output in double quotes for compatibility with JavaScript.</p>

<p><span class='inline-example'>rows</span> - The total number of output rows.
<span class='inline-example'>rows_before_limit_at_least</span> - The minimal number of rows there would have been without a LIMIT. Output only if the query contains LIMIT.
If the query contains GROUP BY, <span class='inline-example'>rows_before_limit_at_least</span> is the exact number of rows there would have been without a LIMIT.</p>

<p><span class='inline-example'>totals</span> - Total values (when using <span class='inline-example'>WITH TOTALS</span>).
<span class='inline-example'>extremes</span> - Extreme values (when <span class='inline-example'>extremes</span> is set to 1).
</p>

<p>This format is only appropriate for writes, not for reads.</p>


<h2>JSONCompact</h2>

<p>Differs from JSON only in that data rows are output in arrays, not in objects. Example: </p>

<pre class='text-example'>
{
        &quot;meta&quot;:
        [
                {
                        &quot;name&quot;: &quot;SearchPhrase&quot;,
                        &quot;type&quot;: &quot;String&quot;
                },
                {
                        &quot;name&quot;: &quot;c&quot;,
                        &quot;type&quot;: &quot;UInt64&quot;
                }
        ],

        &quot;data&quot;:
        [
                [&quot;&quot;, &quot;8267016&quot;],
                [&quot;bath interiors&quot;, &quot;2166&quot;],
                [&quot;yandex&quot;, &quot;1655&quot;],
                [&quot;spring 2014 fashion&quot;, &quot;1549&quot;],
                [&quot;freeform photo&quot;, &quot;1480&quot;]
        ],

        &quot;totals&quot;: [&quot;&quot;,&quot;8873898&quot;],

        &quot;extremes&quot;:
        {
                &quot;min&quot;: [&quot;&quot;,&quot;1480&quot;],
                &quot;max&quot;: [&quot;&quot;,&quot;8267016&quot;]
        },

        &quot;rows&quot;: 5,

        &quot;rows_before_limit_at_least&quot;: 141137
}
</pre>


<h2>Null</h2>

<p>Nothing is output. However, the query is processed, and when using the command-line client, data is transmitted to the client. This is used for tests, including productivity testing. Obviously, this format is only appropriate for writes, not for reads.</p>

</div>
<div class='island'>
<h1>Data types</h1>
</div>
<div class='island'>

<h2>UInt8, UInt16, UInt32, UInt64, Int8, Int16, Int32, Int64</h2>

<p>Fixed-length integers, with or without a sign.</p>


<h2>Float32, Float64</h2>

<p>Floating-point numbers are just like &#39;float&#39; and &#39;double&#39; in the C language.
In contrast to standard SQL, floating-point numbers support &#39;inf&#39;, &#39;-inf&#39;, and even &#39;nan&#39;s.
See the notes on sorting nans in &quot;ORDER BY clause&quot;.
We do not recommend storing floating-point numbers in tables.</p>


<h2>String</h2>

<p>Strings of an arbitrary length. The length is not limited. The value can contain an arbitrary set of bytes, including null bytes.
The String type replaces the types VARCHAR, BLOB, CLOB, and others from other DBMSs.</p>

<h3>Encodings</h3>

<p>ClickHouse doesn&#39;t have the concept of encodings. Strings can contain an arbitrary set of bytes, which are stored and output as-is.
If you need to store texts, we recommend using UTF-8 encoding. At the very least, if your terminal uses UTF-8 (as recommended), you can read and write your values without making conversions.
Similarly, certain functions for working with strings have separate variations that work under the assumption that the string contains a set of bytes representing a UTF-8 encoded text.
For example, the &#39;length&#39; function calculates the string length in bytes, while the &#39;lengthUTF8&#39; function calculates the string length in Unicode code points, assuming that the value is UTF-8 encoded.</p>


<h2>FixedString(N)</h2>

<p>A fixed-length string of N bytes (not characters or code points). N must be a strictly positive natural number.
When reading a string that contains fewer bytes, the string is padded to N bytes by appending null bytes at the right.
When reading a string that contains more bytes, an error message is returned.
When writing a string, null bytes are not trimmed off of the end of the string, but are output.
Note that this behavior differs from MySQL behavior for the CHAR type (where strings are padded with spaces, and the spaces are removed for output).</p>

<p>Fewer functions can work with the FixedString(N) type than with String, so it is less convenient to use.</p>


<h2>Date</h2>

<p>A date. Stored in two bytes as the number of days since 1970-01-01 (unsigned). Allows storing values from just after the beginning of the Unix Epoch to the upper threshold defined by a constant at the compilation stage (currently, this is until the year 2038, but it may be expanded to 2106).
The minimum value is output as 0000-00-00.</p>

<p>The date is stored without the time zone.</p>


<h2>DateTime</h2>

<p>Date with time. Stored in four bytes as a Unix timestamp (unsigned). Allows storing values in the same range as for the Date type. The minimal value is output as 0000-00-00 00:00:00. The time is stored with accuracy up to one second (without leap seconds).</p>

<h3>Time zones</h3>

<p>The date with time is converted from text (divided into component parts) to binary and back, using the system&#39;s time zone at the time the client or server starts. In text format, information about daylight savings is lost.</p>

<p>Supports only those time zones that never had the time differ from UTC for a partial number of hours (without leap seconds) over the entire time range you will be working with.</p>

<p>So when working with a textual date (for example, when saving text dumps), keep in mind that there may be ambiguity during changes for daylight savings time, and there may be problems matching data if the time zone changed.</p>


<h2>Array(T)</h2>

<p>Array of T-type items. The T type can be any type, including an array.
We don&#39;t recommend using multidimensional arrays, because they are not well supported (for example, you can&#39;t store multidimensional arrays in any tables except Memory tables).</p>


<h2>Tuple(T1, T2, ...)</h2>

<p>Tuples can&#39;t be written to tables (other than Memory tables). They are used for temporary column grouping. Columns can be grouped when an IN expression is used in a query, and for specifying certain formal parameters of lambda functions. For more information, see &quot;IN operators&quot; and &quot;Higher order functions&quot;.</p>

<p>Tuples can be output as the result of running a query. In this case, for text formats other than JSON*, values are comma-separated in brackets. In JSON* formats, tuples are output as arrays (in square brackets).</p>


<h2>Nested data structures</h2>

<h2>Nested(Name1 Type1, Name2 Type2, ...)</h2>

<p>A nested data structure is like a nested table. The parameters of a nested data structure - the column names and types - are specified the same way as in a CREATE query. Each table row can correspond to any number of rows in a nested data structure.</p>

<p>Example:</p>

<pre class='text-example'>
CREATE TABLE test.visits
(
    CounterID UInt32,
    StartDate Date,
    Sign Int8,
    IsNew UInt8,
    VisitID UInt64,
    UserID UInt64,
    ...
    Goals Nested
    (
        ID UInt32,
        Serial UInt32,
        EventTime DateTime,
        Price Int64,
        OrderID String,
        CurrencyID UInt32
    ),
    ...
) ENGINE = CollapsingMergeTree(StartDate, intHash32(UserID), (CounterID, StartDate, intHash32(UserID), VisitID), 8192, Sign)
</pre>

<p>This example declares the &#39;Goals&#39; nested data structure, which contains data about conversions (goals reached). Each row in the &#39;visits&#39; table can correspond to zero or any number of conversions.</p>

<p>Only a single nesting level is supported.</p>

<p>In most cases, when working with a nested data structure, its individual columns are specified. To do this, the column names are separated by a dot. These columns make up an array of matching types. All the column arrays of a single nested data structure have the same length.</p>

<p>Example:</p>

<pre class='text-example'>
SELECT
    Goals.ID,
    Goals.EventTime
FROM test.visits
WHERE CounterID = 101500 AND length(Goals.ID) &lt; 5
LIMIT 10

┌─Goals.ID───────────────────────┬─Goals.EventTime───────────────────────────────────────────────────────────────────────────┐
│ [1073752,591325,591325]        │ [&#39;2014-03-17 16:38:10&#39;,&#39;2014-03-17 16:38:48&#39;,&#39;2014-03-17 16:42:27&#39;]                       │
│ [1073752]                      │ [&#39;2014-03-17 00:28:25&#39;]                                                                   │
│ [1073752]                      │ [&#39;2014-03-17 10:46:20&#39;]                                                                   │
│ [1073752,591325,591325,591325] │ [&#39;2014-03-17 13:59:20&#39;,&#39;2014-03-17 22:17:55&#39;,&#39;2014-03-17 22:18:07&#39;,&#39;2014-03-17 22:18:51&#39;] │
│ []                             │ []                                                                                        │
│ [1073752,591325,591325]        │ [&#39;2014-03-17 11:37:06&#39;,&#39;2014-03-17 14:07:47&#39;,&#39;2014-03-17 14:36:21&#39;]                       │
│ []                             │ []                                                                                        │
│ []                             │ []                                                                                        │
│ [591325,1073752]               │ [&#39;2014-03-17 00:46:05&#39;,&#39;2014-03-17 00:46:05&#39;]                                             │
│ [1073752,591325,591325,591325] │ [&#39;2014-03-17 13:28:33&#39;,&#39;2014-03-17 13:30:26&#39;,&#39;2014-03-17 18:51:21&#39;,&#39;2014-03-17 18:51:45&#39;] │
└────────────────────────────────┴───────────────────────────────────────────────────────────────────────────────────────────┘
</pre>

<p>It is easiest to think of a nested data structure as a set of multiple column arrays of the same length.</p>

<p>The only place where a SELECT query can specify the name of an entire nested data structure instead of individual columns is the ARRAY JOIN clause. For more information, see &quot;ARRAY JOIN clause&quot;. Example:</p>

<pre class='text-example'>
SELECT
    Goal.ID,
    Goal.EventTime
FROM test.visits
ARRAY JOIN Goals AS Goal
WHERE CounterID = 101500 AND length(Goals.ID) &lt; 5
LIMIT 10

┌─Goal.ID─┬──────Goal.EventTime─┐
│ 1073752 │ 2014-03-17 16:38:10 │
│  591325 │ 2014-03-17 16:38:48 │
│  591325 │ 2014-03-17 16:42:27 │
│ 1073752 │ 2014-03-17 00:28:25 │
│ 1073752 │ 2014-03-17 10:46:20 │
│ 1073752 │ 2014-03-17 13:59:20 │
│  591325 │ 2014-03-17 22:17:55 │
│  591325 │ 2014-03-17 22:18:07 │
│  591325 │ 2014-03-17 22:18:51 │
│ 1073752 │ 2014-03-17 11:37:06 │
└─────────┴─────────────────────┘
</pre>

<p>You can&#39;t perform SELECT for an entire nested data structure. You can only explicitly list individual columns that are part of it.</p>

<p>For an INSERT query, you should pass all the component column arrays of a nested data structure separately (as if they were individual column arrays). During insertion, the system checks that they have the same length.</p>

<p>For a DESCRIBE query, the columns in a nested data structure are listed separately in the same way.</p>

<p>The ALTER query is very limited for elements in a nested data structure.</p>


<h2>AggregateFunction(name, types_of_arguments...)</h2>

<p>The intermediate state of an aggregate function. To get it, use aggregate functions with the &#39;-State&#39; suffix. For more information, see &quot;AggregatingMergeTree&quot;.</p>


<h2>Special data types</h2>

<p>Special data type values can&#39;t be saved to a table or output in results, but are used as the intermediate result of running a query.</p>

<h3>Set</h3>

<p>Used for the right half of an IN expression.</p>

<h3>Expression</h3>

<p>Used for representing lambda expressions in high-order functions.</p>


<h2>Boolean values</h2>

<p>There isn&#39;t a separate type for boolean values. They use the UInt8 type, restricted to the values 0 or 1.</p>

</div>
<div class='island'>
<h1>Operators</h1>
</div>
<div class='island'>

<p>All operators are transformed to the corresponding functions at the query parsing stage, in accordance with their precedence and associativity.</p>

<h2>Access operators</h2>

<p><span class='inline-example'>a[N]</span> - Access to an array element, arrayElement(a, N) function.
<span class='inline-example'>a.N</span> - Access to a tuple element, tupleElement(a, N) function.</p>

<h2>Numeric negation operator</h2>

<p><span class='inline-example'>-a</span> - negate(a) function</p>

<h2>Multiplication and division operators</h2>

<p><span class='inline-example'>a * b</span> - multiply(a, b) function
<span class='inline-example'>a / b</span> - divide(a, b) function
<span class='inline-example'>a % b</span> - modulo(a, b) function</p>

<h2>Addition and subtraction operators</h2>

<p><span class='inline-example'>a + b</span> - plus(a, b) function
<span class='inline-example'>a - b</span> - minus(a, b) function</p>

<h2>Comparison operators</h2>

<p><span class='inline-example'>a = b</span> - equals(a, b) function
<span class='inline-example'>a == b</span> - equals(a, b) function
<span class='inline-example'>a != b</span> - notEquals(a, b) function
<span class='inline-example'>a &lt;> b</span> - notEquals(a, b) function
<span class='inline-example'>a &lt;= b</span> - lessOrEquals(a, b) function
<span class='inline-example'>a >= b</span> - greaterOrEquals(a, b) function
<span class='inline-example'>a &lt; b</span> - less(a, b) function
<span class='inline-example'>a > b</span> - greater(a, b) function
<span class='inline-example'>a LIKE s</span> - like(a, b) function
<span class='inline-example'>a NOT LIKE s</span> - notLike(a, b) function</p>

<h2>Operators for working with data sets</h2>

<p>See the section &quot;IN operators&quot;.</p>

<p><span class='inline-example'>a IN ...</span> - in(a, b) function
<span class='inline-example'>a NOT IN ...</span> - notIn(a, b) function
<span class='inline-example'>a GLOBAL IN ...</span> - globalIn(a, b) function
<span class='inline-example'>a GLOBAL NOT IN ...</span> - globalNotIn(a, b) function</p>

<h2>Logical negation operator</h2>

<p><span class='inline-example'>NOT a</span> - not(a) function</p>

<h2>Logical &quot;AND&quot; operator</h2>

<p><span class='inline-example'>a AND b</span> - and(a, b) function</p>

<h2>Logical &quot;OR&quot; operator</h2>

<p><span class='inline-example'>a OR b</span> - or(a, b) function</p>

<h2>Conditional operator</h2>

<p><span class='inline-example'>a ? b : c</span> - if(a, b, c) function</p>

<h2>Lambda creation operator</h2>

<p><span class='inline-example'>x -> expr</span> - lambda(x, expr) function</p>

<p>The following operators do not have a priority, since they are brackets:</p>

<h2>Array creation operator</h2>

<p><span class='inline-example'>[x1, ...]</span> - array(x1, ...) function</p>

<h2>Tuple creation operator</h2>

<p><span class='inline-example'>(x1, x2, ...)</span> - tuple(x2, x2, ...) function</p>


<h2>Associativity</h2>

<p>All binary operators have left associativity. For example, &#39;1 + 2 + 3&#39; is transformed to &#39;plus(plus(1, 2), 3)&#39;.
Sometimes this doesn&#39;t work the way you expect. For example, &#39;SELECT 4 > 3 > 2&#39; results in 0.</p>

<p>For efficiency, the &#39;and&#39; and &#39;or&#39; functions accept any number of arguments. The corresponding chains of AND and OR operators are transformed to a single call of these functions.</p>

</div>
<div class='island'>
<h1>Functions</h1>
</div>
<div class='island'>

<p>There are at least* two types of functions - regular functions (they are just called &quot;functions&quot;) and aggregate functions. These are completely different concepts. Regular functions work as if they are applied to each row separately (for each row, the result of the function doesn&#39;t depend on the other rows). Aggregate functions accumulate a set of values from various rows (i.e. they depend on the entire set of rows).</p>

<p>In this section we discuss regular functions. For aggregate functions, see the section &quot;Aggregate functions&quot;.
* - There is a third type of function that the &#39;arrayJoin&#39; function belongs to; table functions can also be mentioned separately.</p>

<h3>Strong typing</h3>

<p>In contrast to standard SQL, ClickHouse has strong typing. In other words, it doesn&#39;t make implicit conversions between types. Each function works for a specific set of types. This means that sometimes you need to use type conversion functions.</p>

<h3>Сommon subexpression elimination</h3>

<p>All expressions in a query that have the same AST (the same record or same result of syntactic parsing) are considered to have identical values. Such expressions are concatenated and executed once. Identical subqueries are also eliminated this way.</p>

<h3>Types of results</h3>

<p>All functions return a single return as the result (not several values, and not zero values). The type of result is usually defined only by the types of arguments, not by the values. Exceptions are the tupleElement function (the a.N operator), and the toFixedString function.</p>

<h3>Constants</h3>

<p>For simplicity, certain functions can only work with constants for some arguments. For example, the right argument of the LIKE operator must be a constant.
Almost all functions return a constant for constant arguments. The exception is functions that generate random numbers.
The &#39;now&#39; function returns different values for queries that were run at different times, but the result is considered a constant, since constancy is only important within a single query.
A constant expression is also considered a constant (for example, the right half of the LIKE operator can be constructed from multiple constants).</p>

<p>Functions can be implemented in different ways for constant and non-constant arguments (different code is executed). But the results for a constant and for a true column containing only the same value should match each other.</p>

<h3>Immutability</h3>

<p>Functions can&#39;t change the values of their arguments - any changes are returned as the result. Thus, the result of calculating separate functions does not depend on the order in which the functions are written in the query.</p>

<h3>Error handling</h3>

<p>Some functions might throw an exception if the data is invalid. In this case, the query is canceled and an error text is returned to the client. For distributed processing, when an exception occurs on one of the servers, the other servers also attempt to abort the query.</p>

<h3>Evaluation of argument expressions</h3>

<p>In almost all programming languages, one of the arguments might not be evaluated for certain operators. This is usually for the operators &amp;&amp;, ||, ?:.
But in ClickHouse, arguments of functions (operators) are always evaluated. This is because entire parts of columns are evaluated at once, instead of calculating each row separately.</p>

<h3>Performing functions for distributed query processing</h3>

<p>For distributed query processing, as many stages of query processing as possible are performed on remote servers, and the rest of the stages (merging intermediate results and everything after that) are performed on the requestor server.</p>

<p>This means that functions can be performed on different servers.
For example, in the query <span class='inline-example'>SELECT <b>f</b>(sum(<b>g</b>(x))) FROM distributed_table GROUP BY <b>h</b>(y)</span>,
- if <span class='inline-example'>distributed_table</span> has at least two shards, the functions <span class='inline-example'>g</span> and <span class='inline-example'>h</span> are performed on remote servers, and the function <span class='inline-example'>f</span> - is performed on the requestor server.
- if <span class='inline-example'>distributed_table</span> has only one shard, all the functions <span class='inline-example'>f</span>, <span class='inline-example'>g</span>, and <span class='inline-example'>h</span> are performed on this shard&#39;s server.</p>

<p>The result of a function usually doesn&#39;t depend on which server it is performed on. However, sometimes this is important.
For example, functions that work with dictionaries use the dictionary that exists on the server they are running on.
Another example is the <span class='inline-example'>hostName</span> function, which returns the name of the server it is running on in order to make GROUP BY by servers in a SELECT query.</p>

<p>If a function in a query is performed on the requestor server, but you need to perform it on remote servers, you can wrap it in an &#39;any&#39; aggregate function or add it to a key in GROUP BY.</p>


<h2>Arithmetic functions</h2>

<p>For all arithmetic functions, the result type is calculated as the smallest number type that the result fits in, if there is such a type. The minimum is taken simultaneously based on the number of bits, whether it is signed, and whether it floats. If there are not enough bits, the highest bit type is taken.</p>

<p>Example:</p>

<pre class='terminal'>
:) SELECT toTypeName(0), toTypeName(0 + 0), toTypeName(0 + 0 + 0), toTypeName(0 + 0 + 0 + 0)

┌─<i class='c15'>toTypeName(0)</i>─┬─<i class='c15'>toTypeName(plus(0, 0))</i>─┬─<i class='c15'>toTypeName(plus(plus(0, 0), 0))</i>─┬─<i class='c15'>toTypeName(plus(plus(plus(0, 0), 0), 0))</i>─┐
│ UInt8         │ UInt16                 │ UInt32                          │ UInt64                                   │
└───────────────┴────────────────────────┴─────────────────────────────────┴──────────────────────────────────────────┘
</pre>

<p>Arithmetic functions work for any pair of types from UInt8, UInt16, UInt32, UInt64, Int8, Int16, Int32, Int64, Float32, or Float64.</p>

<p>Overflow is produced the same way as in C++.</p>


<h3>plus(a, b), a + b operator</h3>

<p>Calculates the sum of the numbers.</p>

<p>You can also add whole numbers with a date or date and time. In the case of a date, adding a whole number means adding the corresponding number of days. For a date with time, it means adding the corresponding number of seconds.</p>

<h3>minus(a, b), a - b operator</h3>

<p>Calculates the difference. The result is always signed.</p>

<p>You can also calculate whole numbers from a date or date with time. The idea is the same - see above for &#39;plus&#39;.</p>

<h3>multiply(a, b), a * b operator</h3>

<p>Calculates the product of the numbers.</p>

<h3>divide(a, b), a / b operator</h3>

<p>Calculates the quotient of the numbers. The result type is always a floating-point type.
It is not integer division. For integer division, use the &#39;intDiv&#39; function.
When dividing by zero you get &#39;inf&#39;, &#39;-inf&#39;, or &#39;nan&#39;.</p>

<h3>intDiv(a, b)</h3>

<p>Calculates the quotient of the numbers. Divides into integers, rounding down (by the absolute value).
When dividing by zero or when dividing a minimal negative number by minus one, an exception is thrown.</p>

<h3>intDivOrZero(a, b)</h3>

<p>Differs from &#39;intDiv&#39; in that it returns zero when dividing by zero or when dividing a minimal negative number by minus one.</p>

<h3>modulo(a, b), a % b operator</h3>

<p>Calculates the remainder after division.
If arguments are floating-point numbers, they are pre-converted to integers by dropping the decimal portion. The remainder is taken in the same sense as in C++. Truncated division is used for negative numbers.
An exception is thrown when dividing by zero or when dividing a minimal negative number by minus one.</p>

<h3>negate(a), -a operator</h3>

<p>Calculates a number with the reverse sign. The result is always signed.</p>

<h3>abs(a)</h3>

<p>Calculates the absolute value of the number &#39;a&#39;. That is, if a&lt; 0, it returns -a.
For unsigned types, it doesn&#39;t do anything. For signed integer types, it returns an unsigned number.</p>

<h2>Bit functions</h2>

<p>Bit functions work for any pair of types from UInt8, UInt16, UInt32, UInt64, Int8, Int16, Int32, Int64, Float32, or Float64.</p>

<p>The result type is an integer with bits equal to the maximum bits of its arguments. If at least one of the arguments is signed, the result is a signed number. If an argument is a floating-point number, it is cast to Int64.</p>

<h3>bitAnd(a, b)</h3>

<h3>bitOr(a, b)</h3>

<h3>bitXor(a, b)</h3>

<h3>bitNot(a)</h3>

<h3>bitShiftLeft(a, b)</h3>

<h3>bitShiftRight(a, b)</h3>


<h2>Comparison functions</h2>

<p>Comparison functions always return 0 or 1 (Uint8).</p>

<p>The following types can be compared:
- numbers
- strings and fixed strings
- dates
- dates with times
within each group, but not between different groups.</p>

<p>For example, you can&#39;t compare a date with a string. You have to use a function to convert the string to a date, or vice versa.</p>

<p>Strings are compared by bytes. A shorter string is smaller than all strings that start with it and that contain at least one more character.</p>

<p>Signed and unsigned numbers are compared the same way as in C++. That is, you can get an incorrect result in some cases. Example: SELECT 9223372036854775807 > -1</p>


<h3>equals, a = b and a == b operator</h3>

<h3>notEquals, a != b and a &lt;> b operator</h3>

<h3>less, &lt; operator</h3>

<h3>greater, > operator</h3>

<h3>lessOrEquals, &lt;= operator</h3>

<h3>greaterOrEquals, >= operator</h3>


<h2>Logical functions</h2>

<p>Logical functions accept any numeric types, but return a UInt8 number equal to 0 or 1.</p>

<p>Zero as an argument is considered &quot;false,&quot; while any non-zero value is considered &quot;true&quot;.</p>


<h3>and, AND operator</h3>

<h3>or, OR operator</h3>

<h3>not, NOT operator</h3>

<h3>xor</h3>


<h2>Type conversion functions</h2>

<h3>toUInt8, toUInt16, toUInt32, toUInt64</h3>
<h3>toInt8, toInt16, toInt32, toInt64</h3>
<h3>toFloat32, toFloat64</h3>
<h3>toDate, toDateTime</h3>
<h3>toString</h3>

<p>Functions for converting between numbers, strings (but not fixed strings), dates, and dates with times. All these functions accept one argument.</p>

<p>When converting to or from a string, the value is formatted or parsed using the same rules as for the TabSeparated format (and almost all other text formats). If the string can&#39;t be parsed, an exception is thrown and the request is canceled.</p>

<p>When converting dates to numbers or vice versa, the date corresponds to the number of days since the beginning of the Unix epoch.
When converting dates with times to numbers or vice versa, the date with time corresponds to the number of seconds since the beginning of the Unix epoch.</p>

<p>As an exception, if converting from UInt32, Int32, UInt64, or Int64 type numbers to Date, and if the number is greater than or equal to 65536, the number is interpreted as a Unix timestamp (and not as the number of days) and is rounded to the date. This allows support for the common occurrence of writing &#39;toDate(unix_timestamp)&#39;, which otherwise would be an error and would require writing the more cumbersome &#39;toDate(toDateTime(unix_timestamp))&#39;.</p>

<p>Conversion between a date and date with time is performed the natural way: by adding a null time or dropping the time.</p>

<p>Conversion between numeric types uses the same rules as assignments between different numeric types in C++.</p>

<h3>toFixedString(s, N)</h3>

<p>Converts a String type argument to a FixedString(N) type (a string with fixed length N). N must be a constant. If the string has fewer bytes than N, it is passed with null bytes to the right. If the string has more bytes than N, an exception is thrown.</p>

<h3>toStringCutToZero(s)</h3>

<p>Accepts a String or FixedString argument. Returns a String and removes the null bytes from the end of the string.</p>

<h3>reinterpretAsUInt8, reinterpretAsUInt16, reinterpretAsUInt32, reinterpretAsUInt64</h3>
<h3>reinterpretAsInt8, reinterpretAsInt16, reinterpretAsInt32, reinterpretAsInt64</h3>
<h3>reinterpretAsFloat32, reinterpretAsFloat64</h3>
<h3>reinterpretAsDate, reinterpretAsDateTime</h3>

<p>These functions accept a string and interpret the bytes placed at the beginning of the string as a number in host order (little endian). If the string isn&#39;t long enough, the functions work as if the string is padded with the necessary number of null bytes. If the string is longer than needed, the extra bytes are ignored. A date is interpreted as the number of days since the beginning of the Unix Epoch, and a date with time is interpreted as the number of seconds since the beginning of the Unix Epoch.</p>

<h3>reinterpretAsString</h3>

<p>This function accepts a number or date or date with time, and returns a string containing bytes representing the corresponding value in host order (little endian). Null bytes are dropped from the end. For example, a UInt32 type value of 255 is a string that is one byte long.</p>


<h2>Functions for working with dates and times</h2>

<h3>toYear</h3>
<p>- Converts a date or date with time to a UInt16 number containing the year number (AD).</p>

<h3>toMonth</h3>
<p>- Converts a date or date with time to a UInt8 number containing the month number (1-12).</p>

<h3>toDayOfMonth</h3>
<p>- Converts a date or date with time to a UInt8 number containing the number of the day of the month (1-31).</p>

<h3>toDayOfWeek</h3>
<p>- Converts a date or date with time to a UInt8 number containing the number of the day of the week (Monday is 1, and Sunday is 7).</p>

<h3>toHour</h3>
<p>- Converts a date with time to a UInt8 number containing the number of the hour in 24-hour time (0-23).
This function assumes that if clocks are moved ahead, it is by one hour and occurs at 2 a.m., and if clocks are moved back, it is by one hour and occurs at 3 a.m. (which is not always true - even in Moscow the clocks were once changed at a different time).</p>

<h3>toMinute</h3>
<p>- Converts a date with time to a UInt8 number containing the number of the minute of the hour (0-59).</p>

<h3>toSecond</h3>
<p>- Converts a date with time to a UInt8 number containing the number of the second in the minute (0-59).
Leap seconds are not accounted for.</p>

<h3>toMonday</h3>
<p>- Rounds down a date or date with time to the nearest Monday.
Returns the date.</p>

<h3>toStartOfMonth</h3>
<p>- Rounds down a date or date with time to the first day of the month.
Returns the date.</p>

<h3>toStartOfQuarter</h3>
<p>- Rounds down a date or date with time to the first day of the quarter.
The first day of the quarter is either 1 January, 1 April, 1 July, or 1 October. Returns the date.</p>

<h3>toStartOfYear</h3>
<p>- Rounds down a date or date with time to the first day of the year.
Returns the date.</p>

<h3>toStartOfMinute</h3>
<p>- Rounds down a date with time to the start of the minute.</p>

<h3>toStartOfHour</h3>
<p>- Rounds down a date with time to the start of the hour.</p>

<h3>toTime</h3>
<p>- Converts a date with time to the date of the start of the Unix Epoch, while preserving the time.</p>

<h3>toRelativeYearNum</h3>
<p>- Converts a date with time or date to the number of the year, starting from a certain fixed point in the past.</p>

<h3>toRelativeMonthNum</h3>
<p>- Converts a date with time or date to the number of the month, starting from a certain fixed point in the past.</p>

<h3>toRelativeWeekNum</h3>
<p>- Converts a date with time or date to the number of the week, starting from a certain fixed point in the past.</p>

<h3>toRelativeDayNum</h3>
<p>- Converts a date with time or date to the number of the day, starting from a certain fixed point in the past.</p>

<h3>toRelativeHourNum</h3>
<p>- Converts a date with time or date to the number of the hour, starting from a certain fixed point in the past.</p>

<h3>toRelativeMinuteNum</h3>
<p>- Converts a date with time or date to the number of the minute, starting from a certain fixed point in the past.</p>

<h3>toRelativeSecondNum</h3>
<p>- Converts a date with time or date to the number of the second, starting from a certain fixed point in the past.</p>

<h3>now</h3>
<p>Accepts zero arguments and returns the current time at one of the moments of request execution.
This function returns a constant, even if the request took a long time to complete.</p>

<h3>today</h3>
<p>Accepts zero arguments and returns the current date at one of the moments of request execution.
The same as &#39;toDate(now())&#39;.</p>

<h3>yesterday</h3>
<p>Accepts zero arguments and returns yesterday&#39;s date at one of the moments of request execution.
The same as &#39;today() - 1&#39;.</p>

<h3>timeSlot</h3>
<p>- Rounds the time to the half hour.
This function is specific to Yandex.Metrica, since half an hour is the minimum amount of time for breaking a session into two sessions if a counter shows a single user&#39;s consecutive pageviews that differ in time by strictly more than this amount. This means that tuples (the counter number, user ID, and time slot) can be used to search for pageviews that are included in the corresponding session.</p>

<h3>timeSlots(StartTime, Duration)</h3>
<p>- For a time interval starting at &#39;StartTime&#39; and continuing for &#39;Duration&#39; seconds, it returns an array of moments in time, consisting of points from this interval rounded down to the half hour.
For example, <span class='inline-example'>timeSlots(toDateTime(&#39;2012-01-01 12:20:00&#39;), 600) = [toDateTime(&#39;2012-01-01 12:00:00&#39;), toDateTime(&#39;2012-01-01 12:30:00&#39;)]</span>.
This is necessary for searching for pageviews in the corresponding session.</p>


<h2>Functions for working with strings</h2>

<h3>empty</h3>
<p>- Returns 1 for an empty string or 0 for a non-empty string.
The result type is UInt8.
A string is considered non-empty if it contains at least one byte, even if this is a space or a null byte.
The function also works for arrays.</p>

<h3>notEmpty</h3>
<p>- Returns 0 for an empty string or 1 for a non-empty string.
The result type is UInt8.
The function also works for arrays.</p>

<h3>length</h3>
<p>- Returns the length of a string in bytes (not in characters, and not in code points).
The result type is UInt64.
The function also works for arrays.</p>

<h3>lengthUTF8</h3>
<p>- Returns the length of a string in Unicode code points (not in characters), assuming that the string contains a set of bytes that make up UTF-8 encoded text. If this assumption is not met, it returns some result (it doesn&#39;t throw an exception).
The result type is UInt64.</p>

<h3>lower</h3>
<p>- Converts ASCII Latin symbols in a string to lowercase.</p>

<h3>upper</h3>
<p>- Converts ASCII Latin symbols in a string to uppercase.</p>

<h3>lowerUTF8</h3>
<p>- Converts a string to lowercase, assuming the string contains a set of bytes that make up a UTF-8 encoded text. It doesn&#39;t detect the language. So for Turkish the result might not be exactly correct.
Note: I don&#39;t remember what it does if the string isn&#39;t UTF-8.</p>

<h3>upperUTF8</h3>
<p>- Converts a string to uppercase, assuming the string contains a set of bytes that make up a UTF-8 encoded text. It doesn&#39;t detect the language. So for Turkish the result might not be exactly correct.
Note: I don&#39;t remember what it does if the string isn&#39;t UTF-8.</p>

<h3>reverse</h3>
<p>- Reverses the string (as a sequence of bytes).</p>

<h3>reverseUTF8</h3>
<p>- Reverses a sequence of Unicode code points, assuming that the string contains a set of bytes representing a UTF-8 text. Otherwise, it does something else (it doesn&#39;t throw an exception).</p>

<h3>concat(s1, s2)</h3>
<p>- Concatenates two strings, without a separator.
If you need to concatenate more than two strings, write &#39;concat&#39; multiple times.</p>

<h3>substring(s, offset, length)</h3>
<p>- Returns a substring starting with the byte from the &#39;offset&#39; index that is &#39;length&#39; bytes long. Character indexing starts from one (as in standard SQL). The &#39;offset&#39; and &#39;length&#39; arguments must be constants.</p>

<h3>substringUTF8(s, offset, length)</h3>
<p>The same as &#39;substring&#39;, but for Unicode code points. Works under the assumption that the string contains a set of bytes representing a UTF-8 encoded text. If this assumption is not met, it returns some result (it doesn&#39;t throw an exception).</p>

<h3>appendTrailingCharIfAbsent(s, c)</h3>
<p>If the <span class='inline-example'>s</span> string is non-empty and does not contain the <span class='inline-example'>c</span> character at the end, it appends the <span class='inline-example'>c</span> character to the end.</p>


<h2>Functions for searching strings</h2>

<p>The search is case-sensitive in all these functions.
The search substring or regular expression must be a constant in all these functions.</p>

<h3>position(haystack, needle)</h3>
<p>- Search for the &#39;needle&#39; substring in the &#39;haystack&#39; string.
Returns the position (in bytes) of the found substring, starting from 1, or returns 0 if the substring was not found.</p>

<h3>positionUTF8(haystack, needle)</h3>
<p>The same as &#39;position&#39;, but the position is returned in Unicode code points. Works under the assumption that the string contains a set of bytes representing a UTF-8 encoded text. If this assumption is not met, it returns some result (it doesn&#39;t throw an exception).</p>

<h3>match(haystack, pattern)</h3>
<p>- Checks whether the string matches the &#39;pattern&#39; regular expression.
The regular expression is re2.
Returns 0 if it doesn&#39;t match, or 1 if it matches.</p>

<p>Note that the backslash symbol (<span class='inline-example'>\</span>) is used for escaping in the regular expression. The same symbol is used for escaping in string literals. So in order to escape the symbol in a regular expression, you must write two backslashes (<span class='inline-example'>\\</span>) in a string literal.</p>

<p>The regular expression works with the string as if it is a set of bytes.
The regular expression can&#39;t contain null bytes.
For patterns to search for substrings in a string, it is better to use LIKE or &#39;position&#39;, since they work much faster.</p>

<h3>extract(haystack, pattern)</h3>
<p>Extracts a fragment of a string using a regular expression. If &#39;haystack&#39; doesn&#39;t match the &#39;pattern&#39; regex, an empty string is returned. If the regex doesn&#39;t contain subpatterns, it takes the fragment that matches the entire regex. Otherwise, it takes the fragment that matches the first subpattern.</p>

<h3>extractAll(haystack, pattern)</h3>
<p>Extracts all the fragments of a string using a regular expression. If &#39;haystack&#39; doesn&#39;t match the &#39;pattern&#39; regex, an empty string is returned. Returns an array of strings consisting of all matches to the regex. In general, the behavior is the same as the &#39;extract&#39; function (it takes the first subpattern, or the entire expression if there isn&#39;t a subpattern).</p>

<h3>like(haystack, pattern), haystack LIKE pattern operator</h3>
<p>- Checks whether a string matches a simple regular expression. The regular expression can contain the metasymbols <span class='inline-example'>%</span> and <span class='inline-example'>_</span>.
<span class='inline-example'>%</span> indicates any quantity of any bytes (including zero characters).
<span class='inline-example'>_</span> indicates any one byte.</p>

<p>Use the backslash (<span class='inline-example'>\</span>) for escaping metasymbols. See the note on escaping in the description of the &#39;match&#39; function.</p>

<p>For regular expressions like<span class='inline-example'>%needle%</span>, the code is more optimal and works as fast as the &#39;position&#39; function. For other regular expressions, the code is the same as for the &#39;match&#39; function.</p>

<h3>notLike(haystack, pattern), haystack NOT LIKE pattern operator</h3>
<p>The same thing as &#39;like&#39;, but negative.</p>


<h2>Functions for searching and replacing in strings</h2>

<h3>replaceOne(haystack, pattern, replacement)</h3>
<p>Replaces the first occurrence, if it exists, of the &#39;pattern&#39; substring in &#39;haystack&#39; with the &#39;replacement&#39; substring.
Hereafter, &#39;pattern&#39; and &#39;replacement&#39; must be constants.</p>

<h3>replaceAll(haystack, pattern, replacement)</h3>
<p>Replaces all occurrences of the &#39;pattern&#39; substring in &#39;haystack&#39; with the &#39;replacement&#39; substring.</p>

<h3>replaceRegexpOne(haystack, pattern, replacement)</h3>
<p>Replacement using the &#39;pattern&#39; regular expression. A re2 regular expression. Replaces only the first occurrence, if it exists.
A pattern can be specified as &#39;replacement&#39;. This pattern can include substitutions \0-\9\.
The substitution \0 includes the entire regular expression.
The substitutions \1-\9 include the subpattern corresponding to the number.
In order to specify the \ symbol in a pattern, you must use a \ symbol to escape it.
Also keep in mind that a string literal requires an extra escape.</p>

<p>Example 1. Converting the date to American format:</p>

<pre class='text-example'>
SELECT DISTINCT
    EventDate,
    replaceRegexpOne(toString(EventDate), &#39;(\\d{4})-(\\d{2})-(\\d{2})&#39;, &#39;\\2/\\3/\\1&#39;) AS res
FROM test.hits
LIMIT 7
FORMAT TabSeparated

2014-03-17      03/17/2014
2014-03-18      03/18/2014
2014-03-19      03/19/2014
2014-03-20      03/20/2014
2014-03-21      03/21/2014
2014-03-22      03/22/2014
2014-03-23      03/23/2014
</pre>

<p>Example 2. Copy the string ten times:</p>

<pre class='text-example'>
SELECT replaceRegexpOne(&#39;Hello, World!&#39;, &#39;.*&#39;, &#39;\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0&#39;) AS res

┌─res────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
│ Hello, World!Hello, World!Hello, World!Hello, World!Hello, World!Hello, World!Hello, World!Hello, World!Hello, World!Hello, World! │
└────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
</pre>

<h3>replaceRegexpAll(haystack, pattern, replacement)</h3>
<p>This does the same thing, but replaces all the occurrences. Example:</p>

<pre class='text-example'>
SELECT replaceRegexpAll(&#39;Hello, World!&#39;, &#39;.&#39;, &#39;\\0\\0&#39;) AS res

┌─res────────────────────────┐
│ HHeelllloo,,  WWoorrlldd!! │
└────────────────────────────┘
</pre>

<p>As an exception, if a regular expression worked on an empty substring, the replacement is not made more than once. Example:</p>

<pre class='text-example'>
SELECT replaceRegexpAll(&#39;Hello, World!&#39;, &#39;^&#39;, &#39;here: &#39;) AS res

┌─res─────────────────┐
│ here: Hello, World! │
└─────────────────────┘
</pre>

<h2>Functions for working with arrays</h2>

<h3>empty</h3>
<p>- Returns 1 for an empty array, or 0 for a non-empty array.
The result type is UInt8.
The function also works for strings.</p>

<h3>notEmpty</h3>
<p>- Returns 0 for an empty array, or 1 for a non-empty array.
The result type is UInt8.
The function also works for strings.</p>

<h3>length</h3>
<p>- Returns the number of items in the array.
4745
The result type is UInt64.
4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459 5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 5493 5494 5495 5496 5497 5498 5499 5500 5501 5502 5503 5504 5505 5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540 5541 5542 5543 5544 5545 5546 5547 5548 5549 5550 5551 5552 5553 5554 5555 5556 5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580 5581 5582 5583 5584 5585 5586 5587 5588 5589 5590 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600 5601 5602 5603 5604 5605 5606 5607 5608 5609 5610 5611 5612 5613 5614 5615 5616 5617 5618 5619 5620 5621 5622 5623 5624 5625 5626 5627 5628 5629 5630 5631 5632 5633 5634 5635 5636 5637 5638 5639 5640 5641 5642 5643 5644 5645 5646 5647 5648 5649 5650 5651 5652 5653 5654 5655 5656 5657 5658 5659 5660 5661 5662 5663 5664 5665 5666 5667 5668 5669 5670 5671 5672 5673 5674 5675 5676 5677 5678 5679 5680 5681 5682 5683 5684 5685 5686 5687 5688 5689 5690 5691 5692 5693 5694 5695 5696 5697 5698 5699 5700 5701 5702 5703 5704 5705 5706 5707 5708 5709 5710 5711 5712 5713 5714 5715 5716 5717 5718 5719 5720 5721 5722 5723 5724 5725 5726 5727 5728 5729 5730 5731 5732 5733 5734 5735 5736 5737 5738 5739 5740 5741 5742 5743 5744 5745 5746 5747 5748 5749 5750 5751 5752 5753 5754 5755 5756 5757 5758 5759 5760 5761 5762 5763 5764 5765 5766 5767 5768 5769 5770 5771 5772 5773 5774 5775 5776 5777 5778 5779 5780 5781 5782 5783 5784 5785 5786 5787 5788 5789 5790 5791 5792 5793 5794 5795 5796 5797 5798 5799 5800 5801 5802 5803 5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815 5816 5817 5818 5819 5820 5821 5822 5823 5824 5825 5826 5827 5828 5829 5830 5831 5832 5833 5834 5835 5836 5837 5838 5839 5840 5841 5842 5843 5844 5845 5846 5847 5848 5849 5850 5851 5852 5853 5854 5855 5856 5857 5858 5859 5860 5861 5862 5863 5864 5865 5866 5867 5868 5869 5870 5871 5872 5873 5874 5875 5876 5877 5878 5879 5880 5881 5882 5883 5884 5885 5886 5887 5888 5889 5890 5891 5892 5893 5894 5895 5896 5897 5898 5899 5900 5901 5902 5903 5904 5905 5906 5907 5908 5909 5910 5911 5912 5913 5914 5915 5916 5917 5918 5919 5920 5921 5922 5923 5924 5925 5926 5927 5928 5929 5930 5931 5932 5933 5934 5935 5936 5937 5938 5939 5940 5941 5942 5943 5944 5945 5946 5947 5948 5949 5950 5951 5952 5953 5954 5955 5956 5957 5958 5959 5960 5961 5962 5963 5964 5965 5966 5967 5968 5969 5970 5971 5972 5973 5974 5975 5976 5977 5978 5979 5980 5981 5982 5983 5984 5985 5986 5987 5988 5989 5990 5991 5992 5993 5994 5995 5996 5997 5998 5999 6000 6001 6002 6003 6004 6005 6006 6007 6008 6009 6010 6011 6012 6013 6014 6015 6016 6017 6018 6019 6020 6021 6022 6023 6024 6025 6026 6027 6028 6029 6030 6031 6032 6033 6034 6035 6036 6037 6038 6039 6040 6041 6042 6043 6044 6045 6046 6047 6048 6049 6050 6051 6052 6053 6054 6055 6056 6057 6058 6059 6060 6061 6062 6063 6064 6065 6066 6067 6068 6069 6070 6071 6072 6073 6074 6075 6076 6077 6078 6079 6080 6081 6082 6083 6084 6085 6086 6087 6088 6089 6090 6091 6092 6093 6094 6095 6096 6097 6098 6099 6100 6101 6102 6103 6104 6105 6106 6107 6108 6109 6110 6111 6112 6113 6114 6115 6116 6117 6118 6119 6120 6121 6122 6123 6124 6125 6126 6127 6128 6129 6130 6131 6132 6133 6134 6135 6136 6137 6138 6139 6140 6141 6142 6143 6144 6145 6146 6147 6148 6149 6150 6151 6152 6153 6154 6155
The function also works for strings.</p>

<h3>emptyArrayUInt8, emptyArrayUInt16, emptyArrayUInt32, emptyArrayUInt64</h3>
<h3>emptyArrayInt8, emptyArrayInt16, emptyArrayInt32, emptyArrayInt64</h3>
<h3>emptyArrayFloat32, emptyArrayFloat64</h3>
<h3>emptyArrayDate, emptyArrayDateTime</h3>
<h3>emptyArrayString</h3>
<p>Accepts zero arguments and returns an empty array of the appropriate type.</p>

<h3>range(N)</h3>
<p>- Returns an array of numbers from 0 to N-1.
Just in case, an exception is thrown if arrays with a total length of more than 100,000,000 elements are created in a data block.</p>

<h3>array(x1, ...), [x1, ...] operator</h3>
<p>- Creates an array from the function arguments.
The arguments must be constants and have types that have the smallest common type. At least one argument must be passed, because otherwise it isn&#39;t clear which type of array to create. That is, you can&#39;t use this function to create an empty array (to do that, use the &#39;emptyArray*&#39; function described above).
Returns an &#39;Array(T)&#39; type result, where &#39;T&#39; is the smallest common type out of the passed arguments.</p>

<h3>arrayElement(arr, n), arr[n] operator</h3>
<p>- Get the element with the index &#39;n&#39; from the array &#39;arr&#39;.
&#39;n&#39; should be any integer type.
Indexes in an array begin from one.
Negative indexes are supported - in this case, it selects the corresponding element numbered from the end. For example, &#39;arr[-1]&#39; is the last item in the array.</p>

<p>If the index goes beyond the array bounds:
- if both arguments are constants, an exception is thrown.
- otherwise, a default value is returned (0 for numbers, an empty string for strings, etc.).</p>

<h3>has(arr, elem)</h3>
<p>- Checking whether the &#39;arr&#39; array has the &#39;elem&#39; element.
Returns 0 if the the element is not in the array, or 1 if it is.
&#39;elem&#39; must be a constant.</p>

<h3>indexOf(arr, x)</h3>
<p>- Returns the index of the &#39;x&#39; element (starting from 1) if it is in the array, or 0 if it is not.</p>

<h3>countEqual(arr, x)</h3>
<p>- Returns the number of elements in the array equal to &#39;x&#39;. Equivalent to <span class='inline-example'>arrayCount(elem -> elem = x, arr)</span>.</p>

<h3>arrayEnumerate(arr)</h3>
<p>- Returns the array <span class='inline-example'>[1, 2, 3, ..., length(arr)]</span></p>

<p>This function is normally used together with ARRAY JOIN. It allows counting something just once for each array after applying ARRAY JOIN. Example: </p>

<pre class='text-example'>
SELECT
    count() AS Reaches,
    countIf(num = 1) AS Hits
FROM test.hits
ARRAY JOIN
    GoalsReached,
    arrayEnumerate(GoalsReached) AS num
WHERE CounterID = 160656
LIMIT 10

┌─Reaches─┬──Hits─┐
│   95606 │ 31406 │
└─────────┴───────┘
</pre>

<p>In this example, Reaches is the number of conversions (the strings received after applying ARRAY JOIN), and Hits is the number of pageviews (strings before ARRAY JOIN). In this particular case, you can get the same result in an easier way:</p>

<pre class='text-example'>
SELECT
    sum(length(GoalsReached)) AS Reaches,
    count() AS Hits
FROM test.hits
WHERE (CounterID = 160656) AND notEmpty(GoalsReached)

┌─Reaches─┬──Hits─┐
│   95606 │ 31406 │
└─────────┴───────┘
</pre>

<p>This function can also be used in higher-order functions. For example, you can use it to get array indexes for elements that match a condition.</p>

<h3>arrayEnumerateUniq(arr, ...)</h3>
<p>- Returns an array the same size as the source array, indicating for each element what its position is among elements with the same value.
For example: <span class='inline-example'>arrayEnumerateUniq([10, 20, 10, 30]) = [1,  1,  2,  1]</span>.</p>

<p>This function is useful when using ARRAY JOIN and aggregation of array elements. Example:</p>

<pre class='text-example'>
SELECT
    Goals.ID AS GoalID,
    sum(Sign) AS Reaches,
    sumIf(Sign, num = 1) AS Visits
FROM test.visits
ARRAY JOIN
    Goals,
    arrayEnumerateUniq(Goals.ID) AS num
WHERE CounterID = 160656
GROUP BY GoalID
ORDER BY Reaches DESC
LIMIT 10

┌──GoalID─┬─Reaches─┬─Visits─┐
│   53225 │    3214 │   1097 │
│ 2825062 │    3188 │   1097 │
│   56600 │    2803 │    488 │
│ 1989037 │    2401 │    365 │
│ 2830064 │    2396 │    910 │
│ 1113562 │    2372 │    373 │
│ 3270895 │    2262 │    812 │
│ 1084657 │    2262 │    345 │
│   56599 │    2260 │    799 │
│ 3271094 │    2256 │    812 │
└─────────┴─────────┴────────┘
</pre>

<p>In this example, each goal ID has a calculation of the number of conversions (each element in the Goals nested data structure is a goal that was reached, which we refer to as a conversion) and the number of sessions. Without ARRAY JOIN, we would have counted the number of sessions as <span class='inline-example'>sum(Sign)</span>. But in this particular case, the rows were multiplied by the nested Goals structure, so in order to count each session one time after this, we apply a condition to the value of the <span class='inline-example'>arrayEnumerateUniq(Goals.ID)</span> function.</p>

<p>The arrayEnumerateUniq function can take multiple arrays of the same size as arguments. In this case, uniqueness is considered for tuples of elements in the same positions in all the arrays.</p>

<pre class='text-example'>
SELECT arrayEnumerateUniq([1, 1, 1, 2, 2, 2], [1, 1, 2, 1, 1, 2]) AS res

┌─res───────────┐
│ [1,2,1,1,2,1] │
└───────────────┘
</pre>

<p>This is necessary when using ARRAY JOIN with a nested data structure and further aggregation across multiple elements in this structure.</p>

<h3>arrayJoin(arr)</h3>
<p>- A special function. See the section &quot;arrayJoin function&quot;.</p>


<h2>Higher-order functions</h2>

<h3><span class='inline-example'>-></span> operator, lambda(params, expr) function</h3>
<p>Allows describing a lambda function for passing to a higher-order function. The left side of the arrow has a formal parameter - any ID, or multiple formal parameters - any IDs in a tuple. The right side of the arrow has an expression that can use these formal parameters, as well as any table columns.

Examples: <span class='inline-example'>x -> 2 * x</span>, <span class='inline-example'>str -> str != Referer</span>.

Higher-order functions can only accept lambda functions as their functional argument.</p>

<p>A lambda function that accepts multiple arguments can be passed to a higher-order function. In this case, the higher-order function is passed several arrays of identical length that these arguments will correspond to.</p>

<p>For all functions other than &#39;arrayMap&#39; and &#39;arrayFilter&#39;, the first argument (the lambda function) can be omitted. In this case, identical mapping is assumed.</p>

<h3>arrayMap(func, arr1, ...)</h3>
<p>Returns an array obtained from the original application of the &#39;func&#39; function to each element in the &#39;arr&#39; array.</p>

<h3>arrayFilter(func, arr1, ...)</h3>
<p>Returns an array containing only the elements in &#39;arr1&#39; for which &#39;func&#39; returns something other than 0.</p>

<p>Examples:</p>

<pre class='text-example'>
SELECT arrayFilter(x -> x LIKE &#39;%World%&#39;, [&#39;Hello&#39;, &#39;abc World&#39;]) AS res

┌─res───────────┐
│ [&#39;abc World&#39;] │
└───────────────┘

SELECT
    arrayFilter(
        (i, x) -> x LIKE &#39;%World%&#39;,
        arrayEnumerate(arr),
        [&#39;Hello&#39;, &#39;abc World&#39;] AS arr)
    AS res

┌─res─┐
│ [2] │
└─────┘
</pre>

<h3>arrayCount([func,] arr1, ...)</h3>
<p>Returns the number of elements in &#39;arr&#39; for which &#39;func&#39; returns something other than 0. If &#39;func&#39; is not specified, it returns the number of non-zero items in the array.</p>

<h3>arrayExists([func,] arr1, ...)</h3>
<p>Returns 1 if there is at least one element in &#39;arr&#39; for which &#39;func&#39; returns something other than 0. Otherwise, it returns 0.</p>

<h3>arrayAll([func,] arr1, ...)</h3>
<p>Returns 1 if &#39;func&#39; returns something other than 0 for all the elements in &#39;arr&#39;. Otherwise, it returns 0.</p>

<h3>arraySum([func,] arr1, ...)</h3>
<p>Returns the sum of the &#39;func&#39; values. If the function is omitted, it just returns the sum of the array elements.</p>

<h3>arrayFirst(func, arr1, ...)</h3>
<p>Returns the first element in the &#39;arr1&#39; array for which &#39;func&#39; returns something other than 0.</p>

<h3>arrayFirstIndex(func, arr1, ...)</h3>
<p>Returns the index of the first element in the &#39;arr1&#39; array for which &#39;func&#39; returns something other than 0.</p>


<h2>Functions for splitting and merging strings and arrays</h2>

<h3>splitByChar(separator, s)</h3>
<p>- Splits a string into substrings, using &#39;separator&#39; as the separator.
&#39;separator&#39; must be a string constant consisting of exactly one character.
Returns an array of selected substrings. Empty substrings may be selected if the separator occurs at the beginning or end of the string, or if there are multiple consecutive separators.</p>

<h3>splitByString(separator, s)</h3>
<p>- The same as above, but it uses a string of multiple characters as the separator. The string must be non-empty.</p>

<h3>alphaTokens(s)</h3>
<p>- Selects substrings of consecutive bytes from the range a-z and A-Z.
Returns an array of selected substrings.</p>


<h2>Functions for working with URLs</h2>

<p>All these functions don&#39;t follow the RFC. They are maximally simplified for improved performance.</p>

<h3>Functions that extract part of a URL</h3>

<p>If there isn&#39;t anything similar in a URL, an empty string is returned.</p>

<h4>protocol</h4>
<p>- Selects the protocol. Examples: http, ftp, mailto, magnet...</p>

<h4>domain</h4>
<p>- Selects the domain.</p>

<h4>domainWithoutWWW</h4>
<p>- Selects the domain and removes no more than one &#39;www.&#39; from the beginning of it, if present.</p>

<h4>topLevelDomain</h4>
<p>- Selects the top-level domain. Example: .ru.</p>

<h4>firstSignificantSubdomain</h4>
<p>- Selects the &quot;first significant subdomain&quot;. This is a non-standard concept specific to Yandex.Metrica.
The first significant subdomain is a second-level domain if it is &#39;com&#39;, &#39;net&#39;, &#39;org&#39;, or &#39;co&#39;. Otherwise, it is a third-level domain.
For example, firstSignificantSubdomain(&#39;https://news.yandex.ru/&#39;) = &#39;yandex&#39;, firstSignificantSubdomain(&#39;https://news.yandex.com.tr/&#39;) = &#39;yandex&#39;.
The list of &quot;insignificant&quot; second-level domains and other implementation details may change in the future.</p>

<h4>cutToFirstSignificantSubdomain</h4>
<p>- Selects the part of the domain that includes top-level subdomains up to the &quot;first significant subdomain&quot; (see the explanation above).
For example, cutToFirstSignificantSubdomain(&#39;https://news.yandex.com.tr/&#39;) = &#39;yandex.com.tr&#39;.</p>

<h4>path</h4>
<p>- Selects the path. Example: /top/news.html
The path does not include the query-string.</p>

<h4>pathFull</h4>
<p>- The same as above, but including query-string and fragment. Example: /top/news.html?page=2#comments</p>

<h4>queryString</h4>
<p>- Selects the query-string. Example: page=1&amp;lr=213.
query-string does not include the first question mark, or # and everything that comes after #.</p>

<h4>fragment</h4>
<p>- Selects the fragment identifier.
fragment does not include the first number sign (#).</p>

<h4>queryStringAndFragment</h4>
<p>- Selects the query-string and fragment identifier. Example: page=1#29390.</p>

<h4>extractURLParameter(URL, name)</h4>
<p>- Selects the value of the &#39;name&#39; parameter in the URL, if present. Otherwise, selects an empty string. If there are many parameters with this name, it returns the first occurrence. This function works under the assumption that the parameter name is encoded in the URL in exactly the same way as in the argument passed.</p>

<h4>extractURLParameters(URL)</h4>
<p>- Gets an array of name=value strings corresponding to the URL parameters. The values are not decoded in any way.</p>

<h4>extractURLParameterNames(URL)</h4>
<p>- Gets an array of name=value strings corresponding to the names of URL parameters. The values are not decoded in any way.</p>

<h4>URLHierarchy(URL)</h4>
<p>- Gets an array containing the URL trimmed to the <span class='inline-example'>/</span>, <span class='inline-example'>?</span> characters in the path and query-string.  Consecutive separator characters are counted as one. The cut is made in the position after all the consecutive separator characters. Example:</p>

<h4>URLPathHierarchy(URL)</h4>
<p>- The same thing, but without the protocol and host in the result. The / element (root) is not included. Example:</p>

<p>This function is used for implementing tree-view reports by URL in Yandex.Metrica.</p>

<pre class='text-example'>
URLPathHierarchy(&#39;https://example.com/browse/CONV-6788&#39;) =
[
    &#39;/browse/&#39;,
    &#39;/browse/CONV-6788&#39;
]
</pre>

<h3>Functions that remove part of a URL.</h3>

<p>If the URL doesn&#39;t have anything similar, the URL remains unchanged.</p>

<h4>cutWWW</h4>
<p>- Removes no more than one &#39;www.&#39; from the beginning of the URL&#39;s domain, if present.</p>

<h4>cutQueryString</h4>
<p>- Removes the query-string. The question mark is also removed.</p>

<h4>cutFragment</h4>
<p>- Removes the fragment identifier. The number sign is also removed.</p>

<h4>cutQueryStringAndFragment</h4>
<p>- Removes the query-string and fragment identifier. The question mark and number sign are also removed.</p>

<h4>cutURLParameter(URL, name)</h4>
<p>- Removes the URL parameter named &#39;name&#39;, if present. This function works under the assumption that the parameter name is encoded in the URL exactly the same way as in the passed argument.</p>


<h2>Functions for working with IP addresses</h2>

<h3>IPv4NumToString(num)</h3>
<p>Takes a UInt32 number. Interprets it as an IPv4 address in big endian. Returns a string containing the corresponding IPv4 address in the format A.B.C.d (dot-separated numbers in decimal form).</p>

<h3>IPv4StringToNum(s)</h3>
<p>The reverse function of IPv4NumToString. If the IPv4 address has an invalid format, it returns 0.</p>

<h3>IPv4NumToStringClassC(num)</h3>
<p>Similar to IPv4NumToString, but using <span class='inline-example'>xxx</span> instead of the last octet. Example:</p>

<pre class='text-example'>
SELECT
    IPv4NumToStringClassC(ClientIP) AS k,
    count() AS c
FROM test.hits
GROUP BY k
ORDER BY c DESC
LIMIT 10

┌─k──────────────┬─────c─┐
│ 83.149.9.xxx   │ 26238 │
│ 217.118.81.xxx │ 26074 │
│ 213.87.129.xxx │ 25481 │
│ 83.149.8.xxx   │ 24984 │
│ 217.118.83.xxx │ 22797 │
│ 78.25.120.xxx  │ 22354 │
│ 213.87.131.xxx │ 21285 │
│ 78.25.121.xxx  │ 20887 │
│ 188.162.65.xxx │ 19694 │
│ 83.149.48.xxx  │ 17406 │
└────────────────┴───────┘
</pre>

<p>Since using &#39;xxx&#39; is highly unusual, this may be changed in the future. We recommend that you don&#39;t rely on the exact format of this fragment.</p>

<h3>IPv6NumToString(x)</h3>
<p>Accepts a FixedString(16) value containing the IPv6 address in binary format. Returns a string containing this address in text format.
IPv6-mapped IPv4 addresses are output in the format <span class='inline-example'>::ffff:111.222.33.44</span>. Examples:</p>

<pre class='text-example'>
SELECT IPv6NumToString(toFixedString(unhex(&#39;2A0206B8000000000000000000000011&#39;), 16)) AS addr

┌─addr─────────┐
│ 2a02:6b8::11 │
└──────────────┘
</pre>

<pre class='text-example'>
SELECT
    IPv6NumToString(ClientIP6 AS k),
    count() AS c
FROM hits_all
WHERE EventDate = today() AND substring(ClientIP6, 1, 12) != unhex(&#39;00000000000000000000FFFF&#39;)
GROUP BY k
ORDER BY c DESC
LIMIT 10

┌─IPv6NumToString(ClientIP6)──────────────┬─────c─┐
│ 2a02:2168:aaa:bbbb::2                   │ 24695 │
│ 2a02:2698:abcd:abcd:abcd:abcd:8888:5555 │ 22408 │
│ 2a02:6b8:0:fff::ff                      │ 16389 │
│ 2a01:4f8:111:6666::2                    │ 16016 │
│ 2a02:2168:888:222::1                    │ 15896 │
│ 2a01:7e00::ffff:ffff:ffff:222           │ 14774 │
│ 2a02:8109:eee:ee:eeee:eeee:eeee:eeee    │ 14443 │
│ 2a02:810b:8888:888:8888:8888:8888:8888  │ 14345 │
│ 2a02:6b8:0:444:4444:4444:4444:4444      │ 14279 │
│ 2a01:7e00::ffff:ffff:ffff:ffff          │ 13880 │
└─────────────────────────────────────────┴───────┘
</pre>

<pre class='text-example'>
SELECT
    IPv6NumToString(ClientIP6 AS k),
    count() AS c
FROM hits_all
WHERE EventDate = today()
GROUP BY k
ORDER BY c DESC
LIMIT 10

┌─IPv6NumToString(ClientIP6)─┬──────c─┐
│ ::ffff:94.26.111.111       │ 747440 │
│ ::ffff:37.143.222.4        │ 529483 │
│ ::ffff:5.166.111.99        │ 317707 │
│ ::ffff:46.38.11.77         │ 263086 │
│ ::ffff:79.105.111.111      │ 186611 │
│ ::ffff:93.92.111.88        │ 176773 │
│ ::ffff:84.53.111.33        │ 158709 │
│ ::ffff:217.118.11.22       │ 154004 │
│ ::ffff:217.118.11.33       │ 148449 │
│ ::ffff:217.118.11.44       │ 148243 │
└────────────────────────────┴────────┘
</pre>

<h3>IPv6StringToNum(s)</h3>
<p>The reverse function of IPv6NumToString. If the IPv6 address has an invalid format, it returns a string of null bytes.
HEX can be uppercase or lowercase.</p>


<h2>Functions for generating pseudo-random numbers</h2>

<p>Non-cryptographic generators of pseudo-random numbers are used.</p>

<p>All the functions accept zero arguments or one argument.
If an argument is passed, it can be any type, and its value is not used for anything.
The only purpose of this argument is to prevent common subexpression elimination, so that two different instances of the same function return different columns with different random numbers.</p>

<h3>rand</h3>
<p>- Returns a pseudo-random UInt32 number, evenly distributed among all UInt32-type numbers.
Uses a linear congruential generator.</p>

<h3>rand64</h3>
<p>- Returns a pseudo-random UInt64 number, evenly distributed among all UInt64-type numbers.
Uses a linear congruential generator.</p>


<h2>Hash functions</h2>

<p>Hash functions can be used for deterministic pseudo-random shuffling of elements.</p>

<h3>halfMD5</h3>
<p>- Calculates the MD5 from a string. Then it takes the first 8 bytes of the hash and interprets them as UInt64 in big endian.
Accepts a String-type argument. Returns UInt64.
This function works fairly slowly (5 million short strings per second per processor core).
If you don&#39;t need MD5 in particular, use the &#39;sipHash64&#39; function instead.</p>

<h3>MD5</h3>
<p>- Calculates the MD5 from a string and returns the resulting set of bytes as FixedString(16).
If you don&#39;t need MD5 in particular, but you need a decent cryptographic 128-bit hash, use the &#39;sipHash128&#39; function instead.
If you need the same result as gives 'md5sum' utility, write <span class='inline-example'>lower(hex(MD5(s)))</span>.</p>

<h3>sipHash64</h3>
<p>- Calculates SipHash from a string.
Accepts a String-type argument. Returns UInt64.
SipHash is a cryptographic hash function. It works at least three times faster than MD5. For more information, see <a href='https://131002.net/siphash/'>https://131002.net/siphash/</a></p>

<h3>sipHash128</h3>
<p>- Calculates SipHash from a string.
Accepts a String-type argument. Returns FixedString(16).
Differs from sipHash64 in that the final xor-folding state is only done up to 128 bytes.</p>

<h3>cityHash64</h3>
<p>- Calculates CityHash64 from a string or a similar hash function for any number of any type of arguments.
For String-type arguments, CityHash is used. This is a fast non-cryptographic hash function for strings with decent quality.
For other types of arguments, a decent implementation-specific fast non-cryptographic hash function is used.
If multiple arguments are passed, the function is calculated using the same rules and chain combinations using the CityHash combinator.
For example, you can compute the checksum of an entire table with accuracy up to the row order: <span class='inline-example'>SELECT sum(cityHash64(*)) FROM table</span>.</p>

<h3>intHash32</h3>
<p>- Calculates a 32-bit hash code from any type of integer.
This is a relatively fast non-cryptographic hash function of average quality for numbers.</p>

<h3>intHash64</h3>
<p>- Calculates a 64-bit hash code from any type of integer.
It works faster than intHash32. Average quality.</p>

<h3>SHA1</h3>
<h3>SHA224</h3>
<h3>SHA256</h3>
<p>- Calculates SHA-1, SHA-224, or SHA-256 from a string and returns the resulting set of bytes as FixedString(20), FixedString(28), or FixedString(32).
The function works fairly slowly (SHA-1 processes about 5 million short strings per second per processor core, while SHA-224 and SHA-256 process about 2.2 million).
We recommend using this function only in cases when you need a specific hash function and you can&#39;t select it.
Even in these cases, we recommend applying the function offline and pre-calculating values when inserting them into the table, instead of applying it in SELECTS.</p>

<h3>URLHash(url[, N])</h3>
<p>A fast, decent-quality non-cryptographic hash function for a string obtained from a URL using some type of normalization.
URLHash(s) - Calculates a hash from a string without one of the trailing symbols /,? or # at the end, if present.
URL Hash(s, N) - Calculates a hash from a string up to the N level in the URL hierarchy, without one of the trailing symbols /,? or # at the end, if present.
Levels are the same as in URLHierarchy. This function is specific to Yandex.Metrica.</p>

<h2>Encoding functions</h2>

<h3>hex</h3>
<p>Accepts a string, number, date, or date with time. Returns a string containing the argument&#39;s hexadecimal representation. Uses uppercase letters A-F. Doesn&#39;t use <span class='inline-example'>0x</span> prefixes or <span class='inline-example'>h</span> suffixes. For strings, all bytes are simply encoded as two hexadecimal numbers. Numbers are converted to big endian (&quot;human readable&quot;) format. For numbers, older zeros are trimmed, but only by entire bytes. For example, <span class='inline-example'>hex(1) = &#39;01&#39;</span>. Dates are encoded as the number of days since the beginning of the Unix Epoch. Dates with times are encoded as the number of seconds since the beginning of the Unix Epoch.</p>

<h3>unhex(str)</h3>
<p>Accepts a string containing any number of hexadecimal digits, and returns a string containing the corresponding bytes. Supports both uppercase and lowercase letters A-F. The number of hexadecimal digits doesn&#39;t have to be even. If it is odd, the last digit is interpreted as the younger half of the 00-0F byte. If the argument string contains anything other than hexadecimal digits, some implementation-defined result is returned (an exception isn&#39;t thrown).
If you want to convert the result to a number, you can use the functions &#39;reverse&#39; and &#39;reinterpretAs<i>Type</i>&#39;.</p>

<h3>bitmaskToList(num)</h3>
<p>Accepts an integer. Returns a string containing the list of powers of two that total the source number when summed. They are comma-separated without spaces in text format, in ascending order.</p>

<h3>bitmaskToArray(num)</h3>
<p>Accepts an integer. Returns an array of UInt64 numbers containing the list of powers of two that total the source number when summed. Numbers in the array are in ascending order.</p>


<h2>Rounding functions</h2>

<h3>floor(x[, N])</h3>
<p>Returns a rounder number that is less than or equal to &#39;x&#39;.</p>
<p>A round number is a multiple of <span class='inline-example'>1 / 10<sup>N</sup></span>, or the nearest number of the appropriate data type if <span class='inline-example'>1 / 10<sup>N</sup></span> isn&#39;t exact.
&#39;N&#39; is an integer constant, optional parameter. By default it is zero, which means to round to an integer.
&#39;N&#39; may be negative.
Examples: <span class='inline-example'>floor(123.45, 1) = 123.4</span>, <span class='inline-example'>floor(123.45, -1) = 120</span>.
&#39;x&#39; is any numeric type. The result is a number of the same type.
For integer arguments, it makes sense to round with a negative &#39;N&#39; value (for non-negative &#39;N&#39;, the function doesn&#39;t do anything).
If rounding causes overflow (for example, <span class='inline-example'>floor(-128, -1)</span>), an implementation-specific result is returned.</p>

<h3>ceil(x[, N])</h3>
<p>Returns the smallest round number that is greater than or equal to &#39;x&#39;. In every other way, it is the same as the &#39;floor&#39; function (see above).</p>

<h3>round(x[, N])</h3>
<p>Returns the round number nearest to &#39;num&#39;, which may be less than, greater than, or equal to &#39;x&#39;.
If &#39;x&#39; is exactly in the middle between the nearest round numbers, one of them is returned (implementation-specific).
The number &#39;-0.&#39; may or may not be considered round (implementation-specific).
In every other way, this function is the same as &#39;floor&#39; and &#39;ceil&#39; described above.</p>

<h3>roundToExp2(num)</h3>
<p>Accepts a number. If the number is less than one, it returns 0. Otherwise, it rounds the number down to the nearest (whole non-negative) degree of two.</p>

<h3>roundDuration(num)</h3>
<p>Accepts a number. If the number is less than one, it returns 0. Otherwise, it rounds the number down to numbers from the set: 1, 10, 30, 60, 120, 180, 240, 300, 600, 1200, 1800, 3600, 7200, 18000, 36000. This function is specific to Yandex.Metrica and used for implementing the report on session length.</p>

<h3>roundAge(num)</h3>
<p>Accepts a number. If the number is less than 18, it returns 0. Otherwise, it rounds the number down to numbers from the set: 18, 25, 35, 45. This function is specific to Yandex.Metrica and used for implementing the report on user age.</p>



<h2>Conditional functions</h2>

<h3>if(cond, then, else), cond ? then : else operator</h3>

<p>Returns &#39;then&#39; if &#39;cond != 0&#39;, or &#39;else&#39; if &#39;cond = 0&#39;.
&#39;cond&#39; must be UInt 8, and &#39;then&#39; and &#39;else&#39; must be a type that has the smallest common type.</p>


<h2>Mathematical functions</h2>

<p>All the functions return a Float64 number. The accuracy of the result is close to the maximum precision possible, but the result might not coincide with the machine representable number nearest to the corresponding real number.</p>

<h3>e()</h3>
<p>Accepts zero arguments and returns a Float64 number close to the <i>e</i> number.</p>

<h3>pi()</h3>
<p>Accepts zero arguments and returns a Float64 number close to <i>π</i>.</p>

<h3>exp(x)</h3>
<p>Accepts a numeric argument and returns a Float64 number close to the exponent of the argument.</p>

<h3>log(x)</h3>
<p>Accepts a numeric argument and returns a Float64 number close to the natural logarithm of the argument.</p>

<h3>exp2(x)</h3>
<p>Accepts a numeric argument and returns a Float64 number close to 2<sup>x</sup>.</p>

<h3>log2(x)</h3>
<p>Accepts a numeric argument and returns a Float64 number close to the binary logarithm of the argument.</p>

<h3>exp10(x)</h3>
<p>Accepts a numeric argument and returns a Float64 number close to 10<sup>x</sup>.</p>

<h3>log10(x)</h3>
<p>Accepts a numeric argument and returns a Float64 number close to the decimal logarithm of the argument.</p>

<h3>sqrt(x)</h3>
<p>Accepts a numeric argument and returns a Float64 number close to the square root of the argument.</p>

<h3>cbrt(x)</h3>
<p>Accepts a numeric argument and returns a Float64 number close to the cubic root of the argument.</p>

<h3>erf(x)</h3>
<p><img src='https://upload.wikimedia.org/math/3/4/4/3443265ce8cb884d9c894401ab15fa71.png'></img>
If &#39;x&#39; is non-negative, then <span class='inline-example'>erf(x / σ√2)</span> is the probability that a random variable having a normal distribution with standard deviation &#39;σ&#39; takes the value that is separated from the expected value by more than &#39;x&#39;.</p>

<p>Example (three sigma rule):</p>

<pre class='text-example'>
SELECT erf(3 / sqrt(2))

┌─erf(divide(3, sqrt(2)))─┐
│      0.9973002039367398 │
└─────────────────────────┘
</pre>

<h3>erfc(x)</h3>
<p>Accepts a numeric argument and returns a Float64 number close to 1 - erf(x), but without loss of precision for large &#39;x&#39; values.</p>

<h3>lgamma(x)</h3>
<p>The logarithm of the gamma function.</p>

<h3>tgamma(x)</h3>
<p>Gamma function.</p>

<h3>sin(x)</h3>
<p>The sine.</p>

<h3>cos(x)</h3>
<p>The cosine.</p>

<h3>tan(x)</h3>
<p>The tangent.</p>

<h3>asin(x)</h3>
<p>The arc sine.</p>

<h3>acos(x)</h3>
<p>The arc cosine.</p>

<h3>atan(x)</h3>
<p>The arc tangent.</p>

<h3>pow(x, y)</h3>
<p>x<sup>y</sup>.</p>

<h2>Functions for working with Yandex.Metrica dictionaries</h2>

<p>In order for the functions below to work, the server config must specify the paths and addresses for getting all the Yandex.Metrica dictionaries. The dictionaries are loaded at the first call of any of these functions. If the reference lists can&#39;t be loaded, an exception is thrown.</p>

<p>For information about creating reference lists, see the section &quot;Dictionaries&quot;.</p>

<h3>Multiple geobases</h3>

<p>ClickHouse supports working with multiple alternative geobases (regional hierarchies) simultaneously, in order to support various perspectives on which countries certain regions belong to.</p>

<p>The &#39;clickhouse-server&#39; config specifies the file with the regional hierarchy:
<span class='inline-example'>&lt;path_to_regions_hierarchy_file>/opt/geo/regions_hierarchy.txt&lt;/path_to_regions_hierarchy_file></span></p>

<p>Besides this file, it also searches for files nearby that have the _ symbol and any suffix appended to the name (before the file extension).
For example, it will also find the file <span class='inline-example'>/opt/geo/regions_hierarchy_ua.txt</span>, if present.</p>

<p><span class='inline-example'>ua</span> is called the dictionary key. For a dictionary without a suffix, the key is an empty string.</p>

<p>All the dictionaries are re-loaded in runtime (once every certain number of seconds, as defined in the builtin_dictionaries_reload_interval config parameter, or once an hour by default). However, the list of available dictionaries is defined one time, when the server starts.</p>

<p>All functions for working with regions have an optional argument at the end - the dictionary key. It is indicated as the <i>geobase</i>.
Example:</p>
<pre class='text-example'>
regionToCountry(RegionID) - Uses the default dictionary: /opt/geo/regions_hierarchy.txt
regionToCountry(RegionID, &#39;&#39;) - Uses the default dictionary: /opt/geo/regions_hierarchy.txt
regionToCountry(RegionID, &#39;ua&#39;) - Uses the dictionary for the &#39;ua&#39; key: /opt/geo/regions_hierarchy_ua.txt
</pre>

<h3>regionToCity(id[, geobase])</h3>

<p>Accepts a UInt32 number - the region ID from the Yandex geobase. If this region is a city or part of a city, it returns the region ID for the appropriate city. Otherwise, returns 0.</p>

<h3>regionToArea(id[, geobase])</h3>

<p>Converts a region to an area (type 5 in the geobase). In every other way, this function is the same as &#39;regionToCity&#39;.</p>

<pre class='text-example'>
SELECT DISTINCT regionToName(regionToArea(toUInt32(number), 'ua'), 'en')
FROM system.numbers
LIMIT 15

┌─regionToName(regionToArea(toUInt32(number), \'ua\'), \'en\')─┐
│                                                              │
│ Moscow and Moscow region                                     │
│ Saint-Petersburg and Leningradskaya oblast                   │
│ Belgorod District                                            │
│ Ivanovo district                                             │
│ Kaluga District                                              │
│ Kostroma District                                            │
│ Kursk District                                               │
│ Lipetsk District                                             │
│ Orel District                                                │
│ Ryazhan District                                             │
│ Smolensk District                                            │
│ Tambov District                                              │
│ Tver District                                                │
│ Tula District                                                │
└──────────────────────────────────────────────────────────────┘
</pre>

<h3>regionToDistrict(id[, geobase])</h3>

<p>Converts a region to a federal district (type 4 in the geobase). In every other way, this function is the same as &#39;regionToCity&#39;.</p>

<pre class='text-example'>
SELECT DISTINCT regionToName(regionToDistrict(toUInt32(number), 'ua'), 'en')
FROM system.numbers
LIMIT 15

┌─regionToName(regionToDistrict(toUInt32(number), \'ua\'), \'en\')─┐
│                                                                  │
│ Central                                                          │
│ Northwest                                                        │
│ South                                                            │
│ North Kavkaz                                                     │
│ Volga Region                                                     │
│ Ural                                                             │
│ Siberian                                                         │
│ Far East                                                         │
│ Scotland                                                         │
│ Faroe Islands                                                    │
│ Flemish Region                                                   │
│ Brussels-Capital Region                                          │
│ Wallonia                                                         │
│ Federation of Bosnia and Herzegovina                             │
└──────────────────────────────────────────────────────────────────┘
</pre>

<h3>regionToCountry(id[, geobase])</h3>

<p>Converts a region to a country. In every other way, this function is the same as &#39;regionToCity&#39;.
Example: <span class='inline-example'>regionToCountry(toUInt32(213)) = 225</span> converts Moscow (213) to Russia (225).</p>

<h3>regionToContinent(id[, geobase])</h3>

<p>Converts a region to a continent. In every other way, this function is the same as &#39;regionToCity&#39;.
Example: <span class='inline-example'>regionToContinent(toUInt32(213)) = 10001</span> converts Moscow (213) to Eurasia (10001).</p>

<h3>regionToPopulation(id[, geobase])</h3>

<p>Gets the population for a region.
The population can be recorded in files with the geobase. See the section &quot;External dictionaries&quot;.
If the population is not recorded for the region, it returns 0.
In the Yandex geobase, the population might be recorded for child regions, but not for parent regions.</p>

<h3>regionIn(lhs, rhs[, geobase])</h3>

<p>Checks whether a &#39;lhs&#39; region belongs to a &#39;rhs&#39; region. Returns a UInt8 number equal to 1 if it belongs, or 0 if it doesn&#39;t belong.
The relationship is reflexive - any region also belongs to itself.</p>

<h3>regionHierarchy(id[, geobase])</h3>

<p>Accepts a UInt32 number - the region ID from the Yandex geobase. Returns an array of region IDs consisting of the passed region and all parents along the chain.
Example: <span class='inline-example'>regionHierarchy(toUInt32(213)) = [213,1,3,225,10001,10000]</span>.</p>

<h3>regionToName(id[, lang])</h3>

<p>Accepts a UInt32 number - the region ID from the Yandex geobase. A string with the name of the language can be passed as a second argument. Supported languages are: ru, en, ua, uk, by, kz, tr. If the second argument is omitted, the language &#39;ru&#39; is used. If the language is not supported, an exception is thrown. Returns a string - the name of the region in the corresponding language. If the region with the specified ID doesn&#39;t exist, an empty string is returned.</p>

<p>&#39;ua&#39; and &#39;uk&#39; mean the same thing - Ukrainian.</p>

<h3>OSToRoot</h3>

<p>Accepts a UInt8 number - the ID of the operating system from the Yandex.Metrica dictionary. If any OS matches the passed number, it returns a UInt8 number - the ID of the corresponding root OS (for example, it converts Windows Vista to Windows). Otherwise, returns 0.</p>

<h3>OSIn(lhs, rhs)</h3>

<p>Checks whether the &#39;lhs&#39; operating system belongs to the &#39;rhs&#39; operating system.</p>

<h3>OSHierarchy</h3>

<p>Accepts a UInt8 number - the ID of the operating system from the Yandex.Metrica dictionary. Returns an array with a hierarchy of operating systems. Similar to the &#39;regionHierarchy&#39; function.</p>

<h3>SEToRoot</h3>

<p>Accepts a UInt8 number - the ID of the search engine from the Yandex.Metrica dictionary. If any search engine matches the passed number, it returns a UInt8 number - the ID of the corresponding root search engine (for example, it converts Yandex.Images to Yandex). Otherwise, returns 0.</p>

<h3>SEIn(lhs, rhs)</h3>

<p>Checks whether the &#39;lhs&#39; search engine belongs to the &#39;rhs&#39; search engine.</p>

<h3>SEHierarchy</h3>

<p>Accepts a UInt8 number - the ID of the search engine from the Yandex.Metrica dictionary. Returns an array with a hierarchy of search engines. Similar to the &#39;regionHierarchy&#39; function.</p>


<h2>Functions for working with external dictionaries</h2>

<p>For more information, see the section &quot;External dictionaries&quot;.</p>

<h3>dictGetUInt8, dictGetUInt16, dictGetUInt32, dictGetUInt64</h3>
<h3>dictGetInt8, dictGetInt16, dictGetInt32, dictGetInt64</h3>
<h3>dictGetFloat32, dictGetFloat64</h3>
<h3>dictGetDate, dictGetDateTime</h3>
<h3>dictGetString</h3>

<p><span class='inline-example'>dictGet<i>T</i>(&#39;dict_name&#39;, &#39;attr_name&#39;, id)</span>
- Gets the value of the &#39;attr_name&#39; attribute from the &#39;dict_name&#39; dictionary by the &#39;id&#39; key.
&#39;dict_name&#39; and &#39;attr_name&#39; are constant strings.
&#39;id&#39; must be UInt64.
If the &#39;id&#39; key is not in the dictionary, it returns the default value set in the dictionary definition.</p>

<h3>dictIsIn</h3>
<p><span class='inline-example'>dictIsIn(&#39;dict_name&#39;, child_id, ancestor_id)</span>
- For the &#39;dict_name&#39; hierarchical dictionary, finds out whether the &#39;child_id&#39; key is located inside &#39;ancestor_id&#39; (or matches &#39;ancestor_id&#39;). Returns UInt8.</p>

<h3>dictGetHierarchy</h3>
<p><span class='inline-example'>dictGetHierarchy(&#39;dict_name&#39;, id)</span>
- For the &#39;dict_name&#39; hierarchical dictionary, returns an array of dictionary keys starting from &#39;id&#39; and continuing along the chain of parent elements. Returns Array(UInt64).</p>


<h2>Functions for working with JSON.</h2>

<p>In Yandex.Metrica, JSON is passed by users as <i>session parameters</i>. There are several functions for working with this JSON. (Although in most of the cases, the JSONs are additionally pre-processed, and the resulting values are put in separate columns in their processed format.) All these functions are based on strong assumptions about what the JSON can be, but they try not to do anything.</p>

<p>The following assumptions are made:

1. The field name (function argument) must be a constant.
2. The field name is somehow canonically encoded in JSON. For example,
<span class='inline-example'>visitParamHas(&#39;{&quot;abc&quot;:&quot;def&quot;}&#39;, &#39;abc&#39;) = 1</span>
, but
<span class='inline-example'>visitParamHas(&#39;{&quot;\\u0061\\u0062\\u0063&quot;:&quot;def&quot;}&#39;, &#39;abc&#39;) = 0</span>
3. Fields are searched for on any nesting level, indiscriminately.  If there are multiple matching fields, the first occurrence is used.
4. JSON doesn&#39;t have space characters outside of string literals.
</p>

<h3>visitParamHas(params, name)</h3>

<p>Checks whether there is a field with the &#39;name&#39; name.</p>

<h3>visitParamExtractUInt(params, name)</h3>

<p>Parses UInt64 from the value of the field named &#39;name&#39;. If this is a string field, it tries to parse a number from the beginning of the string. If the field doesn&#39;t exist, or it exists but doesn&#39;t contain a number, it returns 0.</p>

<h3>visitParamExtractInt(params, name)</h3>

<p>The same as for Int64.</p>

<h3>visitParamExtractFloat(params, name)</h3>

<p>The same as for Float64.</p>

<h3>visitParamExtractBool(params, name)</h3>

<p>Parses a true/false value. The result is UInt8.</p>

<h3>visitParamExtractRaw(params, name)</h3>

<p>Returns the value of a field, including separators. Examples:
<span class='inline-example'>visitParamExtractRaw(&#39;{&quot;abc&quot;:&quot;\\n\\u0000&quot;}&#39;, &#39;abc&#39;) = &#39;&quot;\\n\\u0000&quot;&#39;</span>
<span class='inline-example'>visitParamExtractRaw(&#39;{&quot;abc&quot;:{&quot;def&quot;:[1,2,3]}}&#39;, &#39;abc&#39;) = &#39;{&quot;def&quot;:[1,2,3]}&#39;</span></p>

<h3>visitParamExtractString(params, name)</h3>

<p>Parses the string in double quotes. The value is unescaped. If unescaping failed, it returns an empty string. Examples:
<span class='inline-example'>visitParamExtractString(&#39;{&quot;abc&quot;:&quot;\\n\\u0000&quot;}&#39;, &#39;abc&#39;) = &#39;\n\0&#39;</span>
<span class='inline-example'>visitParamExtractString(&#39;{&quot;abc&quot;:&quot;\\u263a&quot;}&#39;, &#39;abc&#39;) = &#39;&#39;</span>
<span class='inline-example'>visitParamExtractString(&#39;{&quot;abc&quot;:&quot;\\u263&quot;}&#39;, &#39;abc&#39;) = &#39;&#39;</span>
<span class='inline-example'>visitParamExtractString(&#39;{&quot;abc&quot;:&quot;hello}&#39;, &#39;abc&#39;) = &#39;&#39;</span>
Currently, there is no support for code points not from the basic multilingual plane written in the format \uXXXX\uYYYY (they are converted to CESU-8 instead of UTF-8).</p>


<h2>Functions for implementing the IN operator</h2>

<h3>in, notIn, globalIn, globalNotIn</h3>

<p>See the section &quot;IN operators&quot;.</p>


<h3>tuple(x, y, ...), operator (x, y, ...)</h3>
<p>- A function that allows grouping multiple columns.
For columns with the types T1, T2, ..., it returns a Tuple(T1, T2, ...) type tuple containing these columns. There is no cost to execute the function.
Tuples are normally used as intermediate values for an argument of IN operators, or for creating a list of formal parameters of lambda functions. Tuples can&#39;t be written to a table.</p>

<h3>tupleElement(tuple, n), operator x.N</h3>
<p>- A function that allows getting columns from a tuple.
&#39;N&#39; is the column index, starting from 1. &#39;N&#39; must be a constant. &#39;N&#39; must be a strict postive integer no greater than the size of the tuple.
There is no cost to execute the function.</p>


<h2>Other functions</h2>

<h3>hostName()</h3>
<p>- Returns a string with the name of the host that this function was performed on. For distributed processing, this is the name of the remote server host, if the function is performed on a remote server.</p>

<h3>visibleWidth(x)</h3>
<p>- Calculates the approximate width when outputting values to the console in text format (tab-separated). This function is used by the system for implementing Pretty formats.</p>

<h3>toTypeName(x)</h3>
<p>- Gets the type name. Returns a string containing the type name of the passed argument.</p>

<h3>blockSize()</h3>
<p>- Gets the size of the block.
In ClickHouse, queries are always run on blocks (sets of column parts). This function allows getting the size of the block that you called it for.</p>

<h3>materialize(x)</h3>
<p>- Turns a constant into a full column containing just one value.
In ClickHouse, full columns and constants are represented differently in memory. Functions work differently for constant arguments and normal arguments (different code is executed), although the result is almost always the same. This function is for debugging this behavior.</p>

<h3>ignore(...)</h3>
<p>- A function that accepts any arguments and always returns 0.
However, the argument is still calculated. This can be used for benchmarks.</p>

<h3>sleep(seconds)</h3>
<p>Sleeps &#39;seconds&#39; seconds on each data block. You can specify an integer or a floating-point number.</p>

<h3>currentDatabase()</h3>
<p>Returns the name of the current database.
You can use this function in table engine parameters in a CREATE TABLE query where you need to specify the database.</p>

<h3>isFinite(x)</h3>
<p>Accepts Float32 and Float64 and returns UInt8 equal to 1 if the argument is not infinite and not a NaN, otherwise 0.</p>

<h3>isInfinite(x)</h3>
<p>Accepts Float32 and Float64 and returns UInt8 equal to 1 if the argument is infinite, otherwise 0.
Note that 0 is returned for a NaN.</p>

<h3>isNaN(x)</h3>
<p>Accepts Float32 and Float64 and returns UInt8 equal to 1 if the argument is a NaN, otherwise 0.</p>

<h3>bar</h3>
<p>Allows building a unicode-art diagram.</p>

<p>bar(x, min, max, width) - Draws a band with a width proportional to (x - min) and equal to &#39;width&#39; characters when x == max.
min, max - Integer constants. The value must fit in Int64.
width - Constant, positive number, may be a fraction.</p>

<p>The band is drawn with accuracy to one eighth of a symbol. Example:</p>

<pre class='text-example'>
SELECT
    toHour(EventTime) AS h,
    count() AS c,
    bar(c, 0, 600000, 20) AS bar
FROM test.hits
GROUP BY h
ORDER BY h ASC

┌──h─┬──────c─┬─bar────────────────┐
│  0 │ 292907 │ █████████▋         │
│  1 │ 180563 │ ██████             │
│  2 │ 114861 │ ███▋               │
│  3 │  85069 │ ██▋                │
│  4 │  68543 │ ██▎                │
│  5 │  78116 │ ██▌                │
│  6 │ 113474 │ ███▋               │
│  7 │ 170678 │ █████▋             │
│  8 │ 278380 │ █████████▎         │
│  9 │ 391053 │ █████████████      │
│ 10 │ 457681 │ ███████████████▎   │
│ 11 │ 493667 │ ████████████████▍  │
│ 12 │ 509641 │ ████████████████▊  │
│ 13 │ 522947 │ █████████████████▍ │
│ 14 │ 539954 │ █████████████████▊ │
│ 15 │ 528460 │ █████████████████▌ │
│ 16 │ 539201 │ █████████████████▊ │
│ 17 │ 523539 │ █████████████████▍ │
│ 18 │ 506467 │ ████████████████▊  │
│ 19 │ 520915 │ █████████████████▎ │
│ 20 │ 521665 │ █████████████████▍ │
│ 21 │ 542078 │ ██████████████████ │
│ 22 │ 493642 │ ████████████████▍  │
│ 23 │ 400397 │ █████████████▎     │
└────┴────────┴────────────────────┘
</pre>

<h3>transform</h3>
<p>Transforms a value according to the explicitly defined mapping of some elements to other ones.
There are two variations of this function:</p>

<p>1. <span class='inline-example'>transform(x, array_from, array_to, default)</span></p>

<p><span class='inline-example'>x</span> - What to transform.
<span class='inline-example'>array_from</span> - Constant array of values for converting.
<span class='inline-example'>array_to</span> - Constant array of values to convert the values in &#39;from&#39; to.
<span class='inline-example'>default</span> - Constant. Which value to use if &#39;x&#39; is not equal to one of the values in &#39;from&#39;.</p>

<p>&#39;array_from&#39; and &#39;array_to&#39; are arrays of the same size.</p>

<p>Types:
<span class='inline-example'>transform(T, Array(T), Array(U), U) -> U</span></p>

<p>&#39;T&#39; and &#39;U&#39; can be numeric, string, or Date or DateTime types.
Where the same letter is indicated (T or U), for numeric types these might not be matching types, but types that have a common type.
For example, the first argument can have the Int64 type, while the second has the Array(Uint16) type.</p>

<p>If the &#39;x&#39; value is equal to one of the elements in the &#39;array_from&#39; array, it returns the existing element (that is numbered the same) from the &#39;array_to&#39; array. Otherwise, it returns &#39;default&#39;. If there are multiple matching elements in &#39;array_from&#39;, it returns one of the matches.</p>

<p>Example:</p>

<pre class='text-example'>

SELECT
    transform(SearchEngineID, [2, 3], [&#39;Yandex&#39;, &#39;Google&#39;], &#39;Others&#39;) AS title,
    count() AS c
FROM test.hits
WHERE SearchEngineID != 0
GROUP BY title
ORDER BY c DESC

┌─title──┬──────c─┐
│ Yandex │ 498635 │
│ Google │ 229872 │
│ Others │ 104472 │
└────────┴────────┘
</pre>

<p>2. <span class='inline-example'>transform(x, array_from, array_to)</span></p>

<p>Differs from the first variation in that the &#39;default&#39; argument is omitted.
If the &#39;x&#39; value is equal to one of the elements in the &#39;array_from&#39; array, it returns the matching element (that is numbered the same) from the &#39;array_to&#39; array. Otherwise, it returns &#39;x&#39;.</p>

<p>Types:
<span class='inline-example'>transform(T, Array(T), Array(T)) -> T</span></p>

<p>Example:</p>

<pre class='text-example'>

SELECT
    transform(domain(Referer), [&#39;yandex.ru&#39;, &#39;google.ru&#39;, &#39;vk.com&#39;], [&#39;www.yandex&#39;, &#39;ввв.яндекс.рф&#39;, &#39;example.com&#39;]) AS s,
    count() AS c
FROM test.hits
GROUP BY domain(Referer)
ORDER BY count() DESC
LIMIT 10

┌─s──────────────┬───────c─┐
│                │ 2906259 │
│ www.yandex     │  867767 │
│ ███████.ru     │  313599 │
│ mail.yandex.ru │  107147 │
│ ввв.яндекс.рф  │  105668 │
│ ██████.ru      │  100355 │
│ █████████.ru   │   65040 │
│ news.yandex.ru │   64515 │
│ ██████.net     │   59141 │
│ example.com    │   57316 │
└────────────────┴─────────┘
</pre>


<h2>arrayJoin function</h2>

<p>This is a very unusual function.</p>

<p>Normal functions don&#39;t change a set of rows, but just change the values in each row (map). Aggregate functions compress a set of rows (fold or reduce).
The &#39;arrayJoin&#39; function takes each row and generates a set of rows (unfold).</p>

<p>This function takes an array as an argument, and propagates the source row to multiple rows for the number of elements in the array.
All the values in columns are simply copied, except the values in the column where this function is applied - it is replaced with the corresponding array value.</p>

<p>A query can use multiple &#39;arrayJoin&#39; functions. In this case, the transformation is performed multiple times.</p>

<p>Note the ARRAY JOIN syntax in the SELECT query, which provides broader possibilities.</p>

<p>Example:</p>

<pre class='text-example'>
:) SELECT arrayJoin([1, 2, 3] AS src) AS dst, &#39;Hello&#39;, src

SELECT
    arrayJoin([1, 2, 3] AS src) AS dst,
    &#39;Hello&#39;,
    src

┌─dst─┬─\&#39;Hello\&#39;─┬─src─────┐
│   1 │ Hello     │ [1,2,3] │
│   2 │ Hello     │ [1,2,3] │
│   3 │ Hello     │ [1,2,3] │
└─────┴───────────┴─────────┘
</pre>

</div>
<div class='island'>
<h1>Aggregate functions</h1>
</div>
<div class='island'>

<h2>count()</h2>

<p>Counts the number of rows. Accepts zero arguments and returns UInt64.
The only valid way of writing this function is &#39;count()&#39;.
In contrast to standard SQL, you can&#39;t write &#39;count(*)&#39;. This is parsed as if passing all the columns to the &#39;count&#39; function as arguments.
It also doesn&#39;t make sense to write &#39;count(column)&#39;, since ClickHouse doesn&#39;t have NULLs.
The syntax COUNT(DISTINCT x) is not supported. The separate &#39;uniq&#39; aggregate function exists for this purpose.</p>

<p>A &#39;SELECT count() FROM table&#39; query is not optimized, because the number of entries in the table is not stored separately. It will select some small column from the table and count the number of values in it.</p>


<h2>any(x)</h2>

<p>Selects the first encountered value.
The query can be executed in any order and even in a different order each time, so the result of this function is indeterminate.
To get a determinate result, you can use the &#39;min&#39; or &#39;max&#39; function instead of &#39;any&#39;.</p>

<p>In some cases, you can rely on the order of execution. This applies to cases when SELECT comes from a subquery that uses ORDER BY.</p>

<p>When a SELECT query has the GROUP BY clause or at least one aggregate function, ClickHouse (in contrast to MySQL) requires that all expressions in the SELECT, HAVING, and ORDER BY clauses be calculated from keys or from aggregate functions. That is, each column selected from the table must be used either in keys, or inside aggregate functions. To get behavior like in MySQL, you can put the other columns in the &#39;any&#39; aggregate function.</p>


<h2>anyLast(x)</h2>

<p>Selects the last value encountered.
The result is just as indeterminate as for the &#39;any&#39; function.</p>


<h2>min(x)</h2>

<p>Calculates the minimum.</p>


<h2>max(x)</h2>

<p>Calculates the maximum.</p>


<h2>argMin(arg, val)</h2>

<p>Calculates the &#39;arg&#39; value for a minimal &#39;val&#39; value. If there are several different values of &#39;arg&#39; for minimal values of &#39;val&#39;, the first of these values encountered is output.</p>


<h2>argMax(arg, val)</h2>

<p>Calculates the &#39;arg&#39; value for a maximum &#39;val&#39; value. If there are several different values of &#39;arg&#39; for maximum values of &#39;val&#39;, the first of these values encountered is output.</p>


<h2>sum(x)</h2>

<p>Calculates the sum.
Only works for numbers.</p>


<h2>avg(x)</h2>

<p>Calculates the average.
Only works for numbers.
The result is always Float64.</p>


<h2>uniq(x)</h2>

<p>Calculates the approximate number of different values of the argument. Works for numbers, strings, dates, and dates with times.</p>

<p>Uses an adaptive sampling algorithm: for the calculation state, it uses a sample of element hash values with a size up to 65535.
Compared with the widely known HyperLogLog algorithm, this algorithm is less effective in terms of accuracy and memory consumption (even up to proportionality), but it is adaptive. This means that with fairly high accuracy, it consumes less memory during simultaneous computation of cardinality for a large number of data sets whose cardinality has power law distribution (i.e. in cases when most of the data sets are small). This algorithm is also very accurate for data sets with small cardinality (up to 65536) and very efficient on CPU (when computing not too many of these functions, using &#39;uniq&#39; is almost as fast as using other aggregate functions).</p>

<p>There is no compensation for the bias of an estimate, so for large data sets the results are systematically deflated. This function is normally used for computing the number of unique visitors in Yandex.Metrica, so this bias does not play a role.</p>

<p>The result is determinate (it doesn&#39;t depend on the order of query execution).</p>


<h2>uniqHLL12(x)</h2>

<p>Uses the HyperLogLog algorithm to approximate the number of different values of the argument. It uses 2<sup>12</sup> 5-bit cells. The size of the state is slightly more than 2.5 KB.</p>

<p>The result is determinate (it doesn&#39;t depend on the order of query execution).</p>

<p>In most cases, use the &#39;uniq&#39; function. You should only use this function if you understand its advantages well.</p>


<h2>uniqExact(x)</h2>

<p>Calculates the number of different values of the argument, exactly.
There is no reason to fear approximations, so it&#39;s better to use the &#39;uniq&#39; function.
You should use the &#39;uniqExact&#39; function if you definitely need an exact result.</p>

<p>The &#39;uniqExact&#39; function uses more memory than the &#39;uniq&#39; function, because the size of the state has unbounded growth as the number of different values increases.</p>


<h2>groupArray(x)</h2>

<p>Creates an array of argument values.
Values can be added to the array in any (indeterminate) order.</p>

<p>In some cases, you can rely on the order of execution. This applies to cases when SELECT comes from a subquery that uses ORDER BY.</p>


<h2>groupUniqArray(x)</h2>

<p>Creates an array from different argument values. Memory consumption is the same as for the &#39;uniqExact&#39; function.</p>


<h2>median(x)</h2>

<p>Approximates the median. Also see the similar &#39;quantile&#39; function.
Works for numbers, dates, and dates with times.
For numbers it returns Float64, for dates - a date, and for dates with times - a date with time.</p>

<p>Uses reservoir sampling with a reservoir size up to 8192.
If necessary, the result is output with linear approximation from the two neighboring values.
This algorithm proved to be more practical than another well-known algorithm - QDigest.</p>

<p>The result depends on the order of running the query, and is nondeterministic.</p>


<h2>medianTiming(x)</h2>

<p>Calculates the median with fixed accuracy.
Works for numbers. Intended for calculating medians of page loading time in milliseconds.
Also see the similar &#39;quantileTiming&#39; function.</p>

<p>If the value is greater than 30,000 (a page loading time of more than 30 seconds), the result is equated to 30,000.
If the value is less than 1024, the calculation is exact.
If the value is from 1025 to 29,000, the calculation is rounded to a multiple of 16.</p>

<p>In addition, if the total number of values passed to the aggregate function was less than 32, the calculation is exact.</p>

<p>When passing negative values to the function, the behavior is undefined.</p>

<p>The returned value has the Float32 type. If no values were passed to the function (when using &#39;medianTimingIf&#39; or &#39;quantileTimingIf&#39;), &#39;nan&#39; is returned. The purpose of this is to differentiate these instances from zeros. See the note on sorting NaNs in &quot;ORDER BY clause&quot;.</p>

<p>The result is determinate (it doesn&#39;t depend on the order of query execution).</p>

<p>For its purpose (calculating quantiles of page loading times), using this function is more effective and the result is more accurate than for the &#39;median/quantile&#39; function.</p>


<h2>medianDeterministic(x, determinator)</h2>

<p>This function works similarly to the &#39;median&#39; function - it approximates the median. However, in contrast to &#39;median&#39;, the result is deterministic and does not depend on the order of query execution.</p>

<p>To achieve this, the function takes a second argument - the &quot;determinator&quot;. This is a number whose hash is used instead of a random number generator in the reservoir sampling algorithm. For the function to work correctly, the same determinator value should not occur too often. For the determinator, you can use an event ID, user ID, and so on.</p>

<p>Don&#39;t use this function for calculating timings. The &#39;medianTiming&#39;, &#39;quantileTiming&#39;, and &#39;quantilesTiming&#39; functions are better suited to this purpose.</p>


<h2>medianTimingWeighted(x, weight)</h2>

<p>Differs from the &#39;medianTiming&#39; function in that it has a second argument - &quot;weights&quot;. Weight is a non-negative integer.
The result is calculated as if the &#39;x&#39; value were passed &#39;weight&#39; number of times to the &#39;medianTiming&#39; function.</p>


<h2>varSamp(x)</h2>

<p>Calculates the amount <span class='inline-example'>Σ((x - x̅)<sup>2</sup>) / (n - 1)</span>, where &#39;n&#39; is the sample size and &#39;&#39; is the average value of &#39;x&#39;.</p>

<p>It represents an unbiased estimate of the variance of a random variable, if the values passed to the function are a sample of this random amount.</p>

<p>Returns Float64. If n &lt;= 1, it returns +∞.</p>


<h2>varPop(x)</h2>

<p>Calculates the amount <span class='inline-example'>Σ((x - x̅)<sup>2</sup>) / n</span>, where &#39;n&#39; is the sample size and &#39;&#39; is the average value of &#39;x&#39;.</p>

<p>In other words, dispersion for a set of values. Returns Float64.</p>


<h2>stddevSamp(x)</h2>

<p>The result is equal to the square root of &#39;varSamp(x)&#39;.</p>


<h2>stddevPop(x)</h2>

<p>The result is equal to the square root of &#39;varPop(x)&#39;.</p>


<h2>covarSamp(x, y)</h2>

<p>Calculates the value of <span class='inline-example'>Σ((x - x̅)(y - y̅)) / (n - 1)</span>.</p>

<p>Returns Float64. If n &lt;= 1, it returns +∞.</p>


<h2>covarPop(x, y)</h2>

<p>Calculates the value of <span class='inline-example'>Σ((x - x̅)(y - y̅)) / n</span>.</p>


<h2>corr(x, y)</h2>

<p>Calculates the Pearson correlation coefficient: <span class='inline-example'>Σ((x - x̅)(y - y̅)) / sqrt(Σ((x - x̅)<sup>2</sup>) * Σ((y - y̅)<sup>2</sup>))</span>.</p>


<h2>Parametric aggregate functions</h2>

<p>Some aggregate functions can accept not only argument columns (used for compression), but a set of parameters - constants for initialization. The syntax is two pairs of brackets instead of one. The first is for parameters, and the second is for arguments.</p>


<h2>quantile(level)(x)</h2>

<p>Approximates the &#39;level&#39; quantile. &#39;level&#39; is a constant, a floating-point number from 0 to 1. We recommend using a &#39;level&#39; value in the range of 0.01 .. 0.99.
Don&#39;t use a &#39;level&#39; value equal to 0 or 1 - use the &#39;min&#39; and &#39;max&#39; functions for these cases.</p>

<p>The algorithm is the same as for the &#39;median&#39; function. Actually, &#39;quantile&#39; and &#39;median&#39; are internally the same function. You can use the &#39;quantile&#39; function without parameters - in this case, it calculates the median, and you can use the &#39;median&#39; function with parameters - in this case, it calculates the quantile of the set level.</p>

<p>When using multiple &#39;quantile&#39; and &#39;median&#39; functions with different levels in a query, the internal states are not combined (that is, the query works less efficiently than it could). In this case, use the &#39;quantiles&#39; function.</p>


<h2>quantiles(level1, level2, ...)(x)</h2>

<p>Approximates quantiles of all specified levels.
The result is an array containing the corresponding number of values.</p>


<h2>quantileTiming(level)(x)</h2>

<p>Calculates the quantile of &#39;level&#39; using the same algorithm as the &#39;medianTiming&#39; function.</p>


<h2>quantilesTiming(level1, level2, ...)(x)</h2>

<p>Calculates the quantiles of all specified levels using the same algorithm as the &#39;medianTiming&#39; function.</p>


<h2>quantileTimingWeighted(level)(x, weight)</h2>

<p>Calculates the quantile of &#39;level&#39; using the same algorithm as the &#39;medianTimingWeighted&#39; function.</p>


<h2>quantilesTimingWeighted(level1, level2, ...)(x, weight)</h2>

<p>Calculates the quantiles of all specified levels using the same algorithm as the &#39;medianTimingWeighted&#39; function.</p>


<h2>quantileDeterministic(level)(x, determinator)</h2>

<p>Calculates the quantile of &#39;level&#39; using the same algorithm as the &#39;medianDeterministic&#39; function.</p>


<h2>quantilesDeterministic(level1, level2, ...)(x, determinator)</h2>

<p>Calculates the quantiles of all specified levels using the same algorithm as the &#39;medianDeterministic&#39; function.</p>


<h2>sequenceMatch(pattern)(time, cond1, cond2, ...)</h2>

<p>Pattern matching for event chains.</p>

<p>&#39;pattern&#39; is a string containing a pattern to match. The pattern is similar to a regular expression.
&#39;time&#39; is the event time of the DateTime type.
&#39;cond1, cond2 ...&#39; are from one to 32 arguments of the UInt8 type that indicate whether an event condition was met.</p>

<p>The function collects a sequence of events in RAM. Then it checks whether this sequence matches the pattern.
It returns UInt8 - 0 if the pattern isn&#39;t matched, or 1 if it matches.</p>

<p>Example: <span class='inline-example'>sequenceMatch(&#39;(?1).*(?2)&#39;)(EventTime, URL LIKE &#39;%company%&#39;, URL LIKE &#39;%cart%&#39;)</span>
- whether there was a chain of events in which pages with the address in <span class='inline-example'>company</span> were visited earlier than pages with the address in <span class='inline-example'>cart</span>.</p>

<p>This is a degenerate example. You could write it using other aggregate functions:
<span class='inline-example'>minIf(EventTime, URL LIKE &#39;%company%&#39;) &lt; maxIf(EventTime, URL LIKE &#39;%cart%&#39;)</span>.
However, there is no such solution for more complex situations.</p>

<p>Pattern syntax:
<span class='inline-example'>(?1)</span> - Reference to a condition (any number in place of 1).
<span class='inline-example'>.*</span> - Any number of events.
<span class='inline-example'>(?t>=1800)</span> - Time condition.
Any quantity of any type of events is allowed over the specified time.
The operators &lt;, >, &lt;= may be used instead of  >=.
Any number may be specified in place of 1800.</p>

<p>Events that occur during the same second may be put in the chain in any order. This may affect the result of the function.</p>

<h2>uniqUpTo(N)(x)</h2>

<p>Calculates the number of different argument values, if it is less than or equal to N.
If the number of different argument values is greater than N, it returns N + 1.</p>

<p>Recommended for use with small Ns, up to 10. The maximum N value is 100.</p>

<p>For the state of an aggregate function, it uses the amount of memory equal to 1 + N * the size of one value of bytes.
For strings, it stores a non-cryptographic hash of 8 bytes. That is, the calculation is approximated for strings.</p>

<p>It works as fast as possible, except for cases when a large N value is used and the number of unique values is slightly less than N.</p>

<p>Usage example:
Problem: Generate a report that shows only keywords that produced at least 5 unique users.
Solution: Write in the query <span class='inline-example'>GROUP BY SearchPhrase HAVING uniqUpTo(4)(UserID) >= 5</span></p>


<h2>Aggregate function combinators</h2>

<p>The name of an aggregate function can have a suffix appended to it. This changes the way the aggregate function works.
There are <span class='inline-example'>If</span> and <span class='inline-example'>Array</span> combinators. See the sections below.</p>


<h2>-If combinator. Conditional aggregate functions</h2>

<p>The suffix -<span class='inline-example'>If</span> can be appended to the name of any aggregate function. In this case, the aggregate function accepts an extra argument - a condition (Uint8 type). The aggregate function processes only the rows that trigger the condition. If the condition was not triggered even once, it returns a default value (usually zeros or empty strings).</p>

<p>Examples: <span class='inline-example'>countIf(cond)</span>, <span class='inline-example'>avgIf(x, cond)</span>, <span class='inline-example'>quantilesTimingIf(level1, level2)(x, cond)</span>, <span class='inline-example'>argMinIf(arg, val, cond)</span> and so on.</p>

<p>You can use aggregate functions to calculate aggregates for multiple conditions at once, without using subqueries and JOINs.
For example, in Yandex.Metrica, we use conditional aggregate functions for implementing segment comparison functionality.</p>


<h2>-Array combinator. Aggregate functions for array arguments</h2>

<p>The -<span class='inline-example'>Array</span> suffix can be appended to any aggregate function. In this case, the aggregate function takes arguments of the &#39;Array(T)&#39; type (arrays) instead of &#39;T&#39; type arguments. If the aggregate function accepts multiple arguments, this must be arrays of equal lengths. When processing arrays, the aggregate function works like the original aggregate function across all array elements.</p>

<p>Example 1: <span class='inline-example'>sumArray(arr)</span> - Totals all the elements of all &#39;arr&#39; arrays. In this example, it could have been written more simply: <span class='inline-example'>sum(arraySum(arr))</span>.</p>
<p>Example 2: <span class='inline-example'>uniqArray(arr)</span> - Count the number of unique elements in all &#39;arr&#39; arrays. This could be done an easier way: <span class='inline-example'>uniq(arrayJoin(arr))</span>, but it&#39;s not always possible to add &#39;arrayJoin&#39; to a query.</p>

<p>The -<span class='inline-example'>If</span> and -<span class='inline-example'>Array</span> combinators can be used together. However, &#39;Array&#39; must come first, then &#39;If&#39;. Examples: <span class='inline-example'>uniqArrayIf(arr, cond)</span>,  <span class='inline-example'>quantilesTimingArrayIf(level1, level2)(arr, cond)</span>. Due to this order, the &#39;cond&#39; argument can&#39;t be an array.</p>


<h2>-State combinator</h2>

<h2>-Merge combinator</h2>


</div>
<div class='island'>
<h1>Dictionaries</h1>
</div>
<div class='island'>

<p>A dictionary is a mapping (key -> attributes) that can be used in a query as functions. You can think of this as a more convenient and efficient type of JOIN with dimension tables.</p>

<p>There are built-in (internal) and add-on (external) dictionaries.</p>

<h2>Internal dictionaries</h2>

<p>ClickHouse contains a built-in feature for working with a geobase.</p>

<p>This allows you to:
- Use a region&#39;s ID to get its name in the desired language.
- Use a region&#39;s ID to get the ID of a city, area, federal district, country, or continent.
- Check whether a region is part of another region.
- Get a chain of parent regions.</p>

<p>All the functions support &quot;translocality,&quot; the ability to simultaneously use different perspectives on region ownership. For more information, see the section &quot;Functions for working with Yandex.Metrica dictionaries&quot;.</p>

<p>The internal dictionaries are disabled in the default package.
To enable them, uncomment the parameters &#39;path_to_regions_hierarchy_file&#39; and &#39;path_to_regions_names_files&#39; in the server config file.</p>

<p>The geobase is loaded from text files.
If you are Yandex employee, to create them, use the following instructions:
https://███████████.yandex-team.ru/raw/Metrika/ClickHouse_private/master/doc/create_embedded_geobase_dictionaries.txt

<p>Put the regions_hierarchy*.txt files in the path_to_regions_hierarchy_file directory. This configuration parameter must contain the path to the regions_hierarchy.txt file (the default regional hierarchy), and the other files (regions_hierarchy_ua.txt) must be located in the same directory.</p>

<p>Put the regions_names_*.txt files in the path_to_regions_names_files directory.</p>

<p>You can also create these files yourself. The file format is as follows:</p>

<p>regions_hierarchy*.txt: TabSeparated (no header), columns:
- Region ID (UInt32)
- Parent region ID (UInt32)
- Region type (UInt8): 1 - continent, 3 - country, 4 - federal district, 5 - region, 6 - city; other types don&#39;t have values.
- Population (UInt32) - Optional column.</p>

<p>regions_names_*.txt: TabSeparated (no header), columns:
- Region ID (UInt32)
- Region name (String) - Can&#39;t contain tabs or line breaks, even escaped ones.</p>

<p>A flat array is used for storing in RAM. For this reason, IDs shouldn&#39;t be more than a million.</p>

A
Alexey Milovidov 已提交
6156
<p>Dictionaries can be updated without the server restart. However, the set of available dictionaries is not updated. For updates, the file modification times are checked. If a file has changed, the dictionary is updated.
6157 6158 6159 6160 6161 6162 6163 6164 6165 6166 6167 6168 6169 6170 6171 6172 6173 6174 6175 6176 6177 6178 6179 6180 6181 6182 6183 6184 6185 6186 6187 6188 6189 6190 6191 6192 6193 6194 6195 6196 6197 6198 6199 6200 6201 6202 6203 6204 6205 6206 6207 6208 6209 6210 6211 6212 6213 6214 6215 6216 6217 6218 6219 6220 6221 6222 6223 6224 6225 6226 6227 6228 6229 6230 6231 6232 6233 6234 6235 6236 6237 6238 6239 6240 6241 6242 6243 6244 6245 6246 6247 6248 6249 6250 6251 6252 6253 6254 6255 6256 6257 6258 6259 6260 6261 6262 6263 6264 6265 6266 6267 6268 6269 6270 6271 6272 6273 6274 6275 6276 6277 6278 6279 6280 6281 6282 6283 6284 6285 6286 6287 6288 6289 6290 6291 6292 6293 6294 6295 6296 6297 6298 6299 6300 6301 6302 6303 6304 6305 6306 6307 6308 6309 6310 6311 6312 6313 6314 6315 6316 6317 6318 6319 6320 6321 6322 6323 6324 6325 6326 6327 6328 6329 6330 6331 6332 6333 6334 6335 6336 6337 6338 6339 6340 6341 6342 6343 6344 6345 6346 6347 6348 6349 6350 6351 6352 6353 6354 6355 6356 6357 6358 6359 6360 6361 6362 6363 6364 6365 6366 6367 6368 6369 6370 6371 6372 6373 6374 6375 6376 6377 6378 6379 6380 6381 6382 6383 6384 6385 6386 6387 6388 6389 6390 6391
The interval to check for changes is configured in the &#39;builtin_dictionaries_reload_interval&#39; parameter.
Dictionary updates (other than loading at first use) do not block queries. During updates, queries use the old versions of dictionaries. If an error occurs during an update, the error is written to the server log, while queries continue using the old version of dictionaries.</p>

<p>We recommend periodically updating the dictionaries with the geobase. During an update, generate new files and write them to a separate location. When everything is ready, rename them to the files used by the server.</p>

<p>There are also functions for working with OS identifiers and Yandex.Metrica search engines, but they shouldn&#39;t be used.</p>


<h2>External dictionaries</h2>

<p>It is possible to add your own dictionaries from various data sources. The data source for a dictionary can be a file in the local file system, the ClickHouse server, or a MySQL server.
A dictionary can be stored completely in RAM and updated regularly, or it can be partially cached in RAM and dynamically load missing values.</p>

<p>The configuration of external dictionaries is in a separate file or files specified in the &#39;dictionaries_config&#39; configuration parameter.
This parameter contains the absolute or relative path to the file with the dictionary configuration. A relative path is relative to the directory with the server config file. The path can contain wildcards * and ?, in which case all matching files are found. Example: dictionaries/*.xml.</p>

<p>The dictionary configuration, as well as the set of files with the configuration, can be updated without restarting the server. The server checks updates every 5 seconds. This means that dictionaries can be enabled dynamically.</p>

<p>Dictionaries can be created when starting the server, or at first use. This is defined by the &#39;dictionaries_lazy_load&#39; parameter in the main server config file. This parameter is optional, &#39;true&#39; by default. If set to &#39;true&#39;, each dictionary is created at first use. If dictionary creation failed, the function that was using the dictionary throws an exception. If &#39;false&#39;, all dictionaries are created when the server starts, and if there is an error, the server shuts down.</p>

<p>The dictionary config file has the following format:</p>

<pre class='text-example'>
&lt;dictionaries>
	&lt;comment>Optional element with any content; completely ignored.&lt;/comment>

	&lt;!--You can set any number of different dictionaries. -->
	&lt;dictionary>
		&lt;!-- Dictionary name. The dictionary will be accessed for use by this name. -->
		&lt;name>os&lt;/name>

		&lt;!-- Data source. -->
		&lt;source>
			&lt;!-- Source is a file in the local file system. -->
			&lt;file>
				&lt;!-- Path on the local file system. -->
				&lt;path>/opt/dictionaries/os.tsv&lt;/path>
				&lt;!-- Which format to use for reading the file. -->
				&lt;format>TabSeparated&lt;/format>
			&lt;/file>

			&lt;!-- or the source is a table on a MySQL server.
			&lt;mysql>
				&lt;!- - These parameters can be specified outside (common for all replicas) or inside a specific replica - ->
				&lt;port>3306&lt;/port>
				&lt;user>metrika&lt;/user>
				&lt;password>qwerty&lt;/password>
				&lt;!- - Specify from one to any number of replicas for fault tolerance. - ->
				&lt;replica>
					&lt;host>example01-1&lt;/host>
					&lt;priority>1&lt;/priority> &lt;!- - The lower the value, the higher the priority. - ->
				&lt;/replica>
				&lt;replica>
					&lt;host>example01-2&lt;/host>
					&lt;priority>1&lt;/priority>
				&lt;/replica>
				&lt;db>conv_main&lt;/db>
				&lt;table>counters&lt;/table>
			&lt;/mysql>
			-->

			&lt;!-- or the source is a table on the ClickHouse server.
			&lt;clickhouse>
				&lt;host>example01-01-1&lt;/host>
				&lt;port>9000&lt;/port>
				&lt;user>default&lt;/user>
				&lt;password>&lt;/password>
				&lt;db>default&lt;/db>
				&lt;table>counters&lt;/table>
			&lt;/clickhouse>
			&lt;!- - If the address is similar to localhost, the request is made without network interaction. For fault tolerance, you can create a Distributed table on localhost and enter it. - ->
			-->
		&lt;/source>

		&lt;!-- Update interval for fully loaded dictionaries. 0 - never update. -->
		&lt;lifetime>
			&lt;min>300&lt;/min>
			&lt;max>360&lt;/max>
			&lt;!-- The update interval is selected uniformly randomly between min and max, in order to spread out the load when updating dictionaries on a large number of servers. -->
		&lt;/lifetime>

		&lt;!-- or &lt;!- - The update interval for fully loaded dictionaries or invalidation time for cached dictionaries. 0 - never update. - ->
		&lt;lifetime>300&lt;/lifetime>
		-->

		&lt;layout> &lt;!-- Method for storing in memory. -->
			&lt;flat />
			&lt;!-- or &lt;hashed />
			or
			&lt;cache>
				&lt;!- - Cache size in number of cells; rounded up to a degree of two. - ->
				&lt;size_in_cells>1000000000&lt;/size_in_cells>
			&lt;/cache> -->
		&lt;/layout>

		&lt;!-- Structure. -->
		&lt;structure>
			&lt;!-- Description of the column that serves as the dictionary identifier (key). -->
			&lt;id>
				&lt;!-- Column name with ID. -->
				&lt;name>Id&lt;/name>
			&lt;/id>

			&lt;attribute>
				&lt;!-- Column name. -->
				&lt;name>Name&lt;/name>
				&lt;!-- Column type. (How the column is understood when loading. For MySQL, a table can have TEXT, VARCHAR, and BLOB, but these are all loaded as String) -->
				&lt;type>String&lt;/type>
				&lt;!-- Value to use for a non-existing element. In the example, an empty string. -->
				&lt;null_value>&lt;/null_value>
			&lt;/attribute>
			&lt;!-- Any number of attributes can be specified. -->
			&lt;attribute>
				&lt;name>ParentID&lt;/name>
				&lt;type>UInt64&lt;/type>
				&lt;null_value>0&lt;/null_value>
				&lt;!-- Whether it defines a hierarchy - mapping to the parent ID (by default, false). -->
				&lt;hierarchical>true&lt;/hierarchical>
				&lt;!-- The mapping id -> attribute can be considered injective, in order to optimize GROUP BY. (by default, false) -->
				&lt;injective>true&lt;/injective>
			&lt;/attribute>
		&lt;/structure>
	&lt;/dictionary>
&lt;/dictionaries>
</pre>

<p>The dictionary identifier (key attribute) must be a number that fits into UInt64. Compound and string keys are not supported. However, if your dictionary has a complex key, you can hash it and use the hash as the key. You can use View for this purpose (in both ClickHouse and MySQL).</p>

<p>There are three ways to store dictionaries in memory.</p>

<p>1. <span class='inline-example'>flat</span> - As flat arrays.
This is the most effective method. It works if all keys are smaller than 500,000.  If a larger key is discovered when creating the dictionary, an exception is thrown and the dictionary is not created. The dictionary is loaded to RAM in its entirety. The dictionary uses the amount of memory proportional to maximum key value. With the limit of 500,000, memory consumption is not likely to be high. All types of sources are supported. When updating, data (from a file or from a table) is read in its entirety.</p>

<p>2. <span class='inline-example'>hashed</span> - As hash tables.
This method is slightly less effective than the first one. The dictionary is also loaded to RAM in its entirety, and can contain any number of items with any identifiers. In practice, it makes sense to use up to tens of millions of items, while there is enough RAM.
All types of sources are supported. When updating, data (from a file or from a table) is read in its entirety.</p>

<p>3. <span class='inline-example'>cache</span> - This is the least effective method. It is appropriate if the dictionary doesn&#39;t fit in RAM. It is a cache of a fixed number of cells, where frequently-used data can be located. MySQL and ClickHouse sources are supported, but file sources are not supported. When searching a dictionary, the cache is searched first. For each data block, all keys not found in the cache (or expired keys) are collected in a package, which is sent to the source with the query <span class='inline-example'>SELECT attrs... FROM db.table WHERE id IN (k1, k2, ...)</span>. The received data is then written to the cache.</p>

<p>We recommend using the flat method when possible, or hashed. The speed of the dictionaries is impeccable with this type of memory storage.</p>

<p>Use the cache method only in cases when it is unavoidable. The speed of the cache depends strongly on correct settings and the usage scenario. A cache type dictionary only works normally for high enough hit rates (recommended 99% and higher). You can view the average hit rate in the system.dictionaries table. Set a large enough cache size. You will need to experiment to find the right number of cells - select a value, use a query to get the cache completely full, look at the memory consumption (this information is in the system.dictionaries table), then proportionally increase the number of cells so that a reasonable amount of memory is consumed. We recommend MySQL as the source for the cache, because ClickHouse doesn&#39;t handle requests with random reads very well.</p>

<p>In all cases, performance is better if you call the function for working with a dictionary after GROUP BY, and if the attribute being fetched is marked as injective. For a dictionary cache, performance improves if you call the function after LIMIT. To do this, you can use a subquery with LIMIT, and call the function with the dictionary from the outside.</p>

<p>An attribute is called injective if different attribute values correspond to different keys. So when GROUP BY uses a function that fetches an attribute value by the key, this function is automatically taken out of GROUP BY.</p>

<p>When updating dictionaries from a file, first the file modification time is checked, and it is loaded only if the file has changed.
When updating from MySQL, for flat and hashed dictionaries, first a SHOW TABLE STATUS query is made, and the table update time is checked. If it is not NULL, it is compared to the stored time. This works for MyISAM tables, but for InnoDB tables the update time is unknown, so loading from InnoDB is performed on each update.</p>

<p>For cache dictionaries, the expiration (lifetime) of data in the cache can be set. If more time than &#39;lifetime&#39; has passed since loading the data in a cell, the cell&#39;s value is not used, and it is re-requested the next time it needs to be used.</p>

<p>If a dictionary couldn&#39;t be loaded even once, an attempt to use it throws an exception.
If an error occurred during a request to a cached source, an exception is thrown.
Dictionary updates (other than loading for first use) do not block queries. During updates, the old version of a dictionary is used. If an error occurs during an update, the error is written to the server log, and queries continue using the old version of dictionaries.</p>

<p>You can view the list of external dictionaries and their status in the system.dictionaries table.</p>

<p>To use external dictionaries, see the section &quot;Functions for working with external dictionaries&quot;.</p>

<p>Note that you can convert values for a small dictionary by specifying all the contents of the dictionary directly in a SELECT query (see the section &quot;transform function&quot;). This functionality is not related to external dictionaries.</p>


</div>
<div class='island'>
<h1>Settings</h1>
</div>
<div class='island'>

<p>In this section, we review settings that you can make using a SET query or in a config file. Remember that these settings can be set for a session or globally. Settings that can only be made in the server config file are not covered here.</p>


<h2>max_block_size</h2>

<p>In ClickHouse, data is processed by blocks (sets of column parts). The internal processing cycles for a single block are efficient enough, but there are noticeable expenditures on each block. &#39;max_block_size&#39; is a recommendation for what size of block (in number of rows) to load from tables. The block size shouldn&#39;t be too small, so that the expenditures on each block are still noticeable, but not too large, so that the query with LIMIT that is completed after the first block is processed quickly, so that too much memory isn&#39;t consumed when extracting a large number of columns in multiple threads, and so that at least some cache locality is preserved.</p>

<p>By default, it is 65,536.</p>

<p>Blocks the size of &#39;max_block_size&#39; are not always loaded from the table. If it is obvious that less data needs to be retrieved, a smaller block is processed.</p>


<h2>max_insert_block_size</h2>

<p>The size of blocks to form for insertion into a table.
This setting only applies in cases when the server forms the blocks.
For example, for an INSERT via the HTTP interface, the server parses the data format and forms blocks of the specified size.
But when using clickhouse-client, the client parses the data itself, and the &#39;max_insert_block_size&#39; setting on the server doesn&#39;t affect the size of the inserted blocks.
The setting also doesn&#39;t have a purpose when using INSERT SELECT, since data is inserted in the same blocks that are formed after SELECT.</p>

<p>By default, it is 1,048,576.</p>

<p>This is slightly more than &#39;max_block_size&#39;. The reason for this is because certain table engines (*MergeTree) form a data part on the disk for each inserted block, which is a fairly large entity. Similarly, *MergeTree tables sort data during insertion, and a large enough block size allows sorting more data in RAM.</p>


<h2>max_threads</h2>

<p>The maximum number of query processing threads
- excluding threads for retrieving data from remote servers (see the &#39;max_distributed_connections&#39; parameter).</p>

<p>This parameter applies to threads that perform the same stages of the query execution pipeline in parallel.
For example, if reading from a table, evaluating expressions with functions, filtering with WHERE and pre-aggregating for GROUP BY can all be done in parallel using at least &#39;max_threads&#39; number of threads, then &#39;max_threads&#39; are used.</p>

<p>By default, 8.</p>

<p>If less than one SELECT query is normally run on a server at a time, set this parameter to a value slightly less than the actual number of processor cores.</p>

<p>For queries that are completed quickly because of a LIMIT, you can set a lower &#39;max_threads&#39;. For example, if the necessary number of entries are located in every block and max_threads = 8, 8 blocks are retrieved, although it would have been enough to read just one.</p>

<p>The smaller the &#39;max_threads&#39; value, the less memory is consumed.</p>


<h2>max_compress_block_size</h2>

<p>The maximum size of blocks of uncompressed data before compressing for writing to a table. By default, 1,048,576 (1 MiB). If the size is reduced, the compression rate is significantly reduced, the compression and decompression speed increases slightly due to cache locality, and memory consumption is reduced. There usually isn&#39;t any reason to change this setting.</p>

<p>Don&#39;t confuse blocks for compression (a chunk of memory consisting of bytes) and blocks for query processing (a set of rows from a table).</p>


<h2>min_compress_block_size</h2>

<p>For *MergeTree tables. In order to reduce latency when processing queries, a block is compressed when writing the next mark if its size is at least &#39;min_compress_block_size&#39;. By default, 65,536.</p>

<p>The actual size of the block, if the uncompressed data less than &#39;max_compress_block_size&#39; is no less than this value and no less than the volume of data for one mark.</p>

<p>Let&#39;s look at an example. Assume that &#39;index_granularity&#39; was set to 8192 during table creation.</p>

<p>We are writing a UInt32-type column (4 bytes per value). When writing 8192 rows, the total will be 32 KB of data. Since min_compress_block_size = 65,536, a compressed block will be formed for every two marks.</p>

<p>We are writing a URL column with the String type (average size of 60 bytes per value). When writing 8192 rows, the average will be slightly less than 500 KB of data. Since this is more than 65,536, a compressed block will be formed for each mark. In this case, when reading data from the disk in the range of a single mark, extra data won&#39;t be decompressed.</p>

<p>There usually isn&#39;t any reason to change this setting.</p>


<h2>max_query_size</h2>

6392
<p>The maximum part of a query that can be taken to RAM for parsing with the SQL parser.
6393 6394 6395 6396 6397 6398 6399 6400 6401 6402 6403 6404 6405 6406 6407 6408 6409 6410 6411 6412 6413 6414 6415 6416 6417 6418 6419 6420 6421 6422 6423 6424 6425 6426 6427 6428 6429 6430 6431 6432 6433 6434 6435 6436 6437 6438 6439 6440 6441 6442 6443 6444 6445 6446 6447 6448 6449 6450 6451 6452 6453 6454 6455 6456 6457 6458 6459 6460 6461 6462 6463 6464 6465 6466 6467 6468 6469 6470 6471 6472 6473 6474 6475 6476 6477 6478 6479 6480 6481 6482 6483 6484 6485 6486 6487 6488 6489 6490 6491 6492 6493 6494 6495 6496 6497 6498 6499 6500 6501 6502 6503 6504 6505 6506 6507 6508 6509 6510 6511 6512 6513 6514 6515 6516 6517 6518 6519 6520 6521 6522 6523 6524 6525 6526 6527 6528 6529 6530 6531 6532 6533 6534 6535 6536 6537 6538 6539 6540 6541 6542 6543 6544 6545 6546 6547 6548 6549 6550 6551 6552 6553 6554 6555 6556 6557 6558 6559 6560 6561 6562 6563 6564 6565 6566 6567 6568 6569 6570 6571 6572 6573 6574 6575 6576 6577 6578 6579 6580 6581 6582 6583 6584 6585 6586 6587 6588 6589 6590 6591 6592 6593 6594 6595 6596 6597 6598 6599 6600 6601 6602 6603 6604 6605 6606 6607 6608 6609 6610 6611 6612 6613 6614 6615 6616 6617 6618 6619 6620 6621 6622 6623 6624 6625 6626 6627 6628 6629 6630 6631 6632 6633 6634 6635 6636 6637 6638 6639 6640 6641 6642 6643 6644 6645 6646 6647 6648 6649 6650 6651 6652 6653 6654 6655 6656 6657 6658 6659 6660 6661 6662 6663 6664 6665 6666 6667 6668 6669 6670 6671 6672 6673 6674 6675 6676 6677 6678 6679 6680 6681 6682 6683 6684 6685 6686 6687 6688 6689 6690 6691 6692 6693 6694 6695 6696 6697 6698 6699 6700 6701 6702 6703 6704 6705 6706 6707 6708 6709 6710 6711 6712 6713 6714 6715 6716 6717 6718 6719 6720 6721 6722 6723 6724 6725 6726 6727 6728 6729 6730 6731 6732 6733 6734 6735 6736 6737 6738 6739 6740 6741 6742 6743 6744 6745 6746 6747 6748 6749 6750 6751 6752 6753 6754 6755 6756 6757 6758 6759 6760 6761 6762 6763 6764 6765 6766 6767 6768 6769 6770 6771 6772 6773 6774 6775 6776 6777 6778 6779 6780 6781 6782 6783 6784 6785 6786 6787 6788 6789 6790 6791 6792 6793 6794 6795 6796 6797 6798 6799 6800 6801 6802 6803 6804 6805 6806 6807 6808 6809 6810 6811 6812 6813 6814 6815 6816 6817 6818 6819 6820 6821 6822 6823 6824 6825 6826 6827 6828 6829 6830 6831 6832 6833 6834 6835 6836 6837 6838 6839 6840 6841 6842 6843 6844 6845 6846 6847 6848 6849 6850 6851 6852 6853 6854 6855 6856 6857 6858 6859 6860 6861 6862 6863 6864 6865 6866 6867 6868 6869 6870 6871 6872 6873 6874 6875 6876 6877 6878 6879 6880 6881 6882 6883 6884 6885 6886 6887 6888 6889 6890 6891 6892 6893 6894 6895 6896 6897 6898 6899 6900 6901 6902 6903 6904 6905 6906 6907 6908 6909 6910 6911 6912 6913 6914 6915 6916 6917 6918 6919 6920 6921 6922 6923 6924 6925 6926 6927 6928 6929 6930 6931 6932 6933 6934 6935 6936 6937 6938 6939 6940 6941 6942 6943 6944 6945 6946 6947 6948 6949 6950 6951 6952 6953 6954 6955 6956 6957 6958 6959 6960 6961 6962 6963 6964 6965 6966 6967 6968 6969 6970 6971 6972 6973 6974 6975 6976 6977 6978 6979 6980 6981 6982 6983 6984 6985 6986 6987 6988 6989 6990 6991 6992 6993 6994 6995 6996 6997 6998 6999 7000 7001 7002 7003 7004 7005 7006 7007 7008 7009 7010 7011 7012 7013 7014 7015 7016 7017 7018 7019 7020 7021 7022 7023 7024 7025 7026 7027 7028 7029 7030 7031 7032 7033 7034 7035 7036 7037 7038 7039 7040 7041 7042 7043 7044 7045 7046 7047 7048 7049 7050 7051 7052 7053 7054 7055 7056 7057 7058
The INSERT query also contains data for INSERT that is processed by a separate stream parser (that consumes O(1) RAM), which is not included in this restriction.</p>

<p>By default, 64 KiB.</p>


<h2>interactive_delay</h2>

<p>The interval in microseconds for checking whether request execution has been canceled and sending the progress.
By default, 100,000 (check for canceling and send progress ten times per second).</p>


<h2>connect_timeout</h2>
<h2>receive_timeout</h2>
<h2>send_timeout</h2>

<p>Timeouts in seconds on the socket used for communicating with the client.
By default, 10, 300, 300.</p>


<h2>poll_interval</h2>

<p>Lock in a wait loop for the specified number of seconds.
By default, 10.</p>


<h2>max_distributed_connections</h2>

<p>The maximum number of simultaneous connections with remote servers for distributed processing of a single query to a single Distributed table. We recommend setting a value no less than the number of servers in the cluster.</p>

<p>By default, 100.</p>


<p>The following parameters are only used when creating Distributed tables (and when launching a server), so there is no reason to change them at runtime.</p>

<h2>distributed_connections_pool_size</h2>

<p>The maximum number of simultaneous connections with remote servers for distributed processing of all queries to a single Distributed table. We recommend setting a value no less than the number of servers in the cluster.</p>

<p>By default, 128.</p>


<h2>connect_timeout_with_failover_ms</h2>

<p>The timeout in milliseconds for connecting to a remote server for a Distributed table engine, if the &#39;shard&#39; and &#39;replica&#39; sections are used in the cluster definition.
If unsuccessful, several attempts are made to connect to various replicas.
By default, 50.</p>


<h2>connections_with_failover_max_tries</h2>

<p>The maximum number of connection attempts with each replica, for the Distributed table engine.
By default, 3.</p>


<h2>extremes</h2>

<p>Whether to count extreme values (the minimums and maximums in columns of a query result).
Accepts 0 or 1. By default, 0 (disabled).
For more information, see the section &quot;Extreme values&quot;.</p>


<h2>use_uncompressed_cache</h2>

<p>Whether to use a cache of uncompressed blocks. Accepts 0 or 1. By default, 0 (disabled).
The uncompressed cache (only for tables in the MergeTree family) allows significantly reducing latency and increasing throughput when working with a large number of short queries. Enable this setting for users who send frequent short requests. Also pay attention to the &#39;uncompressed_cache_size&#39; configuration parameter (only set in the config file) - the size of uncompressed cache blocks. By default, it is 8 GiB. The uncompressed cache is filled in as needed; the least-used data is automatically deleted.</p>

<p>For queries that read at least a somewhat large volume of data (one million rows or more), the uncompressed cache is disabled automatically in order to save space for truly small queries. So you can keep the &#39;use_uncompressed_cache&#39; setting always set to 1.</p>


<h2>replace_running_query</h2>

<p>When using the HTTP interface, the &#39;query_id&#39; parameter can be passed. This is any string that serves as the query identifier.
If a query from the same user with the same &#39;query_id&#39; already exists at this time, the behavior depends on the &#39;replace_running_query&#39; parameter.</p>

<p>0 (default) - Throw an exception (don&#39;t allow the query to run if a query with the same &#39;query_id&#39; is already running).
1 - Cancel the old query and start running the new one.</p>

<p>Yandex.Metrica uses this parameter set to 1 for implementing suggestions for segmentation conditions. After entering the next character, if the old query hasn&#39;t finished yet, it should be canceled.</p>


<h2>load_balancing</h2>

<p>Which replicas (among healthy replicas) to preferably send a query to (on the first attempt) for distributed processing.</p>

<p><b>random</b> (default)</p>

<p>The number of errors is counted for each replica. The query is sent to the replica with the fewest errors, and if there are several of these, to any one of them.
Disadvantages: Server proximity is not accounted for; if the replicas have different data, you will also get different data.</p>

<p><b>nearest_hostname</b></p>

<p>The number of errors is counted for each replica. Every 5 minutes, the number of errors is integrally divided by 2. Thus, the number of errors is calculated for a recent time with exponential smoothing. If there is one replica with a minimal number of errors (i.e. errors occurred recently on the other replicas), the query is sent to it. If there are multiple replicas with the same minimal number of errors, the query is sent to the replica with a host name that is most similar to the server&#39;s host name in the config file (for the number of different characters in identical positions, up to the minimum length of both host names).</p>

<p>As an example, example01-01-1 and example01-01-2.yandex.ru are different in one position, while example01-01-1 and example01-02-2 differ in two places.
This method might seem a little stupid, but it doesn&#39;t use external data about network topology, and it doesn&#39;t compare IP addresses, which would be complicated for our IPv6 addresses.</p>

<p>Thus, if there are equivalent replicas, the closest one by name is preferred.
We can also assume that when sending a query to the same server, in the absence of failures, a distributed query will also go to the same servers. So even if different data is placed on the replicas, the query will return mostly the same results.</p>

<p><b>in_order</b></p>

<p>Replicas are accessed in the same order as they are specified. The number of errors does not matter. This method is appropriate when you know exactly which replica is preferable.</p>


<h2>totals_mode</h2>

<p>How to calculate TOTALS when HAVING is present, as well as when max_rows_to_group_by and group_by_overflow_mode = &#39;any&#39; are present.
See the section &quot;WITH TOTALS modifier&quot;.</p>

<h2>totals_auto_threshold</h2>

<p>The threshold for totals_mode = &#39;auto&#39;.
See the section &quot;WITH TOTALS modifier&quot;.</p>


<h2>default_sample</h2>

<p>A floating-point number from 0 to 1. By default, 1.
Allows setting a default sampling coefficient for all SELECT queries.
(For tables that don&#39;t support sampling, an exception will be thrown.)
If set to 1, default sampling is not performed.</p>


<h2>Restrictions on query complexity</h2>

<p>Restrictions on query complexity are part of the settings.
They are used in order to provide safer execution from the user interface.
Almost all the restrictions only apply to SELECTs.
For distributed query processing, restrictions are applied on each server separately.</p>

<p>Restrictions on the &quot;maximum amount of something&quot; can take the value 0, which means &quot;unrestricted&quot;.
Most restrictions also have an &#39;overflow_mode&#39; setting, meaning what to do when the limit is exceeded.
It can take one of two values: &#39;throw&#39; or &#39;break&#39;. Restrictions on aggregation (group_by_overflow_mode) also have the value &#39;any&#39;.
throw - Throw an exception (default).
break - Stop executing the query and return the partial result, as if the source data ran out.
any (only for group_by_overflow_mode) - Continuing aggregation for the keys that got into the set, but don&#39;t add new keys to the set.</p>


<h3>readonly</h3>

<p>If set to 1, run only queries that don&#39;t change data or settings.
As an example, SELECT and SHOW queries are allowed, but INSERT and SET are forbidden.
After you write <span class='inline-example'>SET readonly = 1</span>, you can&#39;t disable readonly mode in the current session.</p>

<p>When using the GET method in the HTTP interface, &#39;readonly = 1&#39; is set automatically. In other words, for queries that modify data, you can only use the POST method. You can send the query itself either in the POST body, or in the URL parameter.</p>

<h3>max_memory_usage</h3>

<p>The maximum amount of memory consumption when running a query on a single server. By default, 10 GB.</p>

<p>The setting doesn&#39;t consider the volume of available memory or the total volume of memory on the machine.
The restriction applies to a single query within a single server.
You can use SHOW PROCESSLIST to see the current memory consumption for each query.
In addition, the peak memory consumption is tracked for each query and written to the log.</p>

<p>Certain cases of memory consumption are not tracked:
- Large constants (for example, a very long string constant).
- The states of &#39;groupArray&#39; aggregate functions, and also &#39;quantile&#39; (it is tracked for &#39;quantileTiming&#39;).</p>

<p>Memory consumption is not fully considered for aggregate function states &#39;min&#39;, &#39;max&#39;, &#39;any&#39;, &#39;anyLast&#39;, &#39;argMin&#39;, and &#39;argMax&#39; from String and Array arguments.</p>


<h3>max_rows_to_read</h3>

<p>The following restrictions can be checked on each block (instead of on each row). That is, the restrictions can be broken a little.
When running a query in multiple threads, the following restrictions apply to each thread separately.</p>

<p>Maximum number of rows that can be read from a table when running a query.</p>

<h3>max_bytes_to_read</h3>

<p>Maximum number of bytes (uncompressed data) that can be read from a table when running a query.</p>

<h3>read_overflow_mode</h3>

<p>What to do when the volume of data read exceeds one of the limits: &#39;throw&#39; or &#39;break&#39;. By default, throw.</p>

<h3>max_rows_to_group_by</h3>

<p>Maximum number of unique keys received from aggregation. This setting lets you limit memory consumption when aggregating.</p>

<h3>group_by_overflow_mode</h3>

<p>What to do when the number of unique keys for aggregation exceeds the limit: &#39;throw&#39;, &#39;break&#39;, or &#39;any&#39;. By default, throw.
Using the &#39;any&#39; value lets you run an approximation of GROUP BY. The quality of this approximation depends on the statistical nature of the data.</p>

<h3>max_rows_to_sort</h3>

<p>Maximum number of rows before sorting. This allows you to limit memory consumption when sorting.</p>

<h3>max_bytes_to_sort</h3>

<p>Maximum number of bytes before sorting.</p>

<h3>sort_overflow_mode</h3>

<p>What to do if the number of rows received before sorting exceeds one of the limits: &#39;throw&#39; or &#39;break&#39;. By default, throw.</p>

<h3>max_result_rows</h3>

<p>Limit on the number of rows in the result. Also checked for subqueries, and on remote servers when running parts of a distributed query.</p>

<h3>max_result_bytes</h3>

<p>Limit on the number of bytes in the result. The same as the previous setting.</p>

<h3>result_overflow_mode</h3>

<p>What to do if the volume of the result exceeds one of the limits: &#39;throw&#39; or &#39;break&#39;. By default, throw.
Using &#39;break&#39; is similar to using LIMIT.</p>

<h3>max_execution_time</h3>

<p>Maximum query execution time in seconds.
At this time, it is not checked for one of the sorting stages, or when merging and finalizing aggregate functions.</p>

<h3>timeout_overflow_mode</h3>

<p>What to do if the query is run longer than &#39;max_execution_time&#39;: &#39;throw&#39; or &#39;break&#39;. By default, throw.</p>

<h3>min_execution_speed</h3>

<p>Minimal execution speed in rows per second. Checked on every data block when &#39;timeout_before_checking_execution_speed&#39; expires. If the execution speed is lower, an exception is thrown.</p>

<h3>timeout_before_checking_execution_speed</h3>

<p>Checks that execution speed is not too slow (no less than &#39;min_execution_speed&#39;), after the specified time in seconds has expired.</p>

<h3>max_columns_to_read</h3>

<p>Maximum number of columns that can be read from a table in a single query. If a query requires reading a greater number of columns, it throws an exception.</p>

<h3>max_temporary_columns</h3>

<p>Maximum number of temporary columns that must be kept in RAM at the same time when running a query, including constant columns. If there are more temporary columns than this, it throws an exception.</p>

<h3>max_temporary_non_const_columns</h3>

<p>The same thing as &#39;max_temporary_columns&#39;, but without counting constant columns.
Note that constant columns are formed fairly often when running a query, but they require approximately zero computing resources.</p>

<h3>max_subquery_depth</h3>

<p>Maximum nesting depth of subqueries. If subqueries are deeper, an exception is thrown. By default, 100.</p>

<h3>max_pipeline_depth</h3>

<p>Maximum pipeline depth. Corresponds to the number of transformations that each data block goes through during query processing. Counted within the limits of a single server. If the pipeline depth is greater, an exception is thrown. By default, 1000.</p>

<h3>max_ast_depth</h3>

<p>Maximum nesting depth of a query syntactic tree. If exceeded, an exception is thrown. At this time, it isn&#39;t checked during parsing, but only after parsing the query. That is, a syntactic tree that is too deep can be created during parsing, but the query will fail. By default, 1000.</p>

<h3>max_ast_elements</h3>

<p>Maximum number of elements in a query syntactic tree. If exceeded, an exception is thrown.
In the same way as the previous setting, it is checked only after parsing the query. By default, 10,000.</p>

<h3>max_rows_in_set</h3>

<p>Maximum number of rows for a data set in the IN clause created from a subquery.</p>

<h3>max_bytes_in_set</h3>

<p>Maximum number of bytes (uncompressed data) used by a set in the IN clause created from a subquery.</p>

<h3>set_overflow_mode</h3>

<p>What to do when the amount of data exceeds one of the limits: &#39;throw&#39; or &#39;break&#39;. By default, throw.</p>

<h3>max_rows_in_distinct</h3>

<p>Maximum number of different rows when using DISTINCT.</p>

<h3>max_bytes_in_distinct</h3>

<p>Maximum number of bytes used by a hash table when using DISTINCT.</p>

<h3>distinct_overflow_mode</h3>

<p>What to do when the amount of data exceeds one of the limits: &#39;throw&#39; or &#39;break&#39;. By default, throw.</p>

<h3>max_rows_to_transfer</h3>

<p>Maximum number of rows that can be passed to a remote server or saved in a temporary table when using GLOBAL IN.</p>

<h3>max_bytes_to_transfer</h3>

<p>Maximum number of bytes (uncompressed data) that can be passed to a remote server or saved in a temporary table when using GLOBAL IN.</p>

<h3>transfer_overflow_mode</h3>

<p>What to do when the amount of data exceeds one of the limits: &#39;throw&#39; or &#39;break&#39;. By default, throw.</p>


<h2>Settings profiles</h2>

<p>A settings profile is a collection of settings grouped under the same name. Each ClickHouse user has a profile.
To apply all the settings in a profile, set &#39;profile&#39;. Example:</p>

<pre class='text-example'>
SET profile = &#39;web&#39;
</pre>

<p>- Load the &#39;web&#39; profile. That is, set all the options belonging to the &#39;web&#39; profile.</p>

<p>Settings profiles are declared in the user config file. This is normally &#39;users.xml&#39;.
Example:</p>

<pre class='text-example'>
&lt;!-- Settings profiles. -->
&lt;profiles>
	&lt;!-- Default settings -->
	&lt;default>
		&lt;!-- Maximum number of threads for executing a single query. -->
		&lt;max_threads>8&lt;/max_threads>
	&lt;/default>
	&lt;!-- Settings for queries from the user interface -->
	&lt;web>
		&lt;max_rows_to_read>1000000000&lt;/max_rows_to_read>
		&lt;max_bytes_to_read>100000000000&lt;/max_bytes_to_read>
		&lt;max_rows_to_group_by>1000000&lt;/max_rows_to_group_by>
		&lt;group_by_overflow_mode>any&lt;/group_by_overflow_mode>
		&lt;max_rows_to_sort>1000000&lt;/max_rows_to_sort>
		&lt;max_bytes_to_sort>1000000000&lt;/max_bytes_to_sort>
		&lt;max_result_rows>100000&lt;/max_result_rows>
		&lt;max_result_bytes>100000000&lt;/max_result_bytes>
		&lt;result_overflow_mode>break&lt;/result_overflow_mode>
		&lt;max_execution_time>600&lt;/max_execution_time>
		&lt;min_execution_speed>1000000&lt;/min_execution_speed>
		&lt;timeout_before_checking_execution_speed>15&lt;/timeout_before_checking_execution_speed>
		&lt;max_columns_to_read>25&lt;/max_columns_to_read>
		&lt;max_temporary_columns>100&lt;/max_temporary_columns>
		&lt;max_temporary_non_const_columns>50&lt;/max_temporary_non_const_columns>
		&lt;max_subquery_depth>2&lt;/max_subquery_depth>
		&lt;max_pipeline_depth>25&lt;/max_pipeline_depth>
		&lt;max_ast_depth>50&lt;/max_ast_depth>
		&lt;max_ast_elements>100&lt;/max_ast_elements>
		&lt;readonly>1&lt;/readonly>
	&lt;/web>
&lt;/profiles>
</pre>

<p>In the example, two profiles are set: &#39;default&#39; and &#39;web&#39;. The &#39;default&#39; profile has a special purpose - it must always be present and is applied when starting the server. In other words, the &#39;default&#39; profile contains default settings. The &#39;web&#39; profile is a regular profile that can be set using the SET query or using a URL parameter in an HTTP query.

Settings profiles can inherit from each other. To use inheritance, indicate the &#39;profile&#39; setting before the other settings that are listed in the profile.</p>

</div>
<div class='island'>
<h1>Configuration files</h1>
</div>
<div class='island'>

<p>The main server config file is &#39;config.xml&#39;. It resides in the /etc/clickhouse-server/ directory.</p>

<p>Certain settings can be overridden in the *.xml and *.conf files from the &#39;conf.d&#39; and &#39;config.d&#39; directories next to the config.
The &#39;replace&#39; and &#39;remove&#39; attributes can be specified for the elements of these config files.
If neither is specified, it combines the contents of elements recursively, replacing values of duplicate children.
If &#39;replace&#39; is specified, it replaces the entire element with the specified one.
If &#39;remove&#39; is specified, it deletes the element.</p>

<p>The config can also define &quot;substitutions&quot;. If an element has the &#39;incl&#39; attribute, the corresponding substitution from the file will be used as the value. By default, the path to the file with substitutions is &#39;/etc/metrika.xml&#39;. This can be changed in the config in the &#39;include_from&#39; element. The substitution values are specified in  &#39;/yandex/<i>substitution_name</i>&#39; elements of this file.</p>

<p>The &#39;config.xml&#39; file can specify a separate config with user settings, profiles, and quotas. The relative path to this config is set in the &#39;users_config&#39; element. By default, it is &#39;users.xml&#39;. If &#39;users_config&#39; is omitted, the user settings, profiles, and quotas are specified directly in &#39;config.xml&#39;. The server tracks changes to &#39;users_config&#39; and reloads it in runtime. That is, you can add or change users and their settings without relaunching the server.</p>

<p>For &#39;users.config&#39;, overrides and substitutions may also exist in files from the &#39;<i>users_config</i>.d&#39; directory (for example, &#39;users.d&#39;). Note that the server tracks updates only directly in the &#39;users.xml&#39; file, so all the possible overrides are not updated in runtime.</p>

<p>For each config file, the server also generates <i>file</i>-preprocessed.xml files on launch. These files contain all the completed substitutions and overrides, and they are intended for informational use. The server itself does not use these files, and you do not need to edit them.
</p>

</div>
<div class='island'>
<h1>Access rights</h1>
</div>
<div class='island'>

<p>Users and access rights are set up in the user config. This is usually &#39;users.xml&#39;.</p>

<p>Users are recorded in the &#39;users&#39; section. Let&#39;s look at part of the &#39;users.xml&#39; file:</p>

<pre class='text-example'>
&lt;!-- Users and ACL. -->
&lt;users>
	&lt;!-- If the username is not specified, the default user is used. -->
	&lt;default>
		&lt;!-- Password (in plaintext). May be empty. -->
		&lt;password>&lt;/password>

		&lt;!-- List of networks that access is allowed from. Each list item has one of the following forms:
			&lt;ip> IP address or subnet mask. For example, 222.111.222.3 or 10.0.0.1/8 or 2a02:6b8::3 or 2a02:6b8::3/64.
			&lt;host> Host name. Example: example01. A DNS query is made for verification, and all received address are compared to the client address.
			&lt;host_regexp> Regex for host names. For example, ^example\d\d-\d\d-\d\.yandex\.ru$
				A DNS PTR query is made to verify the client address and the regex is applied to the result.
				Then another DNS query is made for the result of the PTR query, and all received address are compared to the client address.
				We strongly recommend that the regex ends with \.yandex\.ru$. If you are installing ClickHouse independently, here you should specify:
			&lt;networks>
				&lt;ip>::/0&lt;/ip>
			&lt;/networks> -->

		&lt;networks incl=&quot;networks&quot; />
		&lt;!-- Settings profile for the user. -->
		&lt;profile>default&lt;/profile>
		&lt;!-- Quota for the user. -->
		&lt;quota>default&lt;/quota>
	&lt;/default>

	&lt;!-- For queries from the user interface. -->
	&lt;web>
		&lt;password>&lt;/password>
		&lt;networks incl=&quot;networks&quot; />
		&lt;profile>web&lt;/profile>
		&lt;quota>default&lt;/quota>
	&lt;/web>
</pre>

<p>Here we can see that two users are declared: &#39;default&#39; and &#39;web&#39;. We added the &#39;web&#39; user ourselves.
The &#39;default&#39; user is chosen in cases when the username is not passed, so this user must be present in the config file. The &#39;default&#39; user is also used for distributed query processing - the system accesses remote servers under this username. So the &#39;default&#39; user must have an empty password and must not have substantial restrictions or quotas - otherwise, distributed queries will fail.</p>

<p>The password is specified in open format directly in the config. In this regard, you should not consider these passwords as providing security against potential malicious attacks. Rather, they are necessary for protection from Yandex employees.</p>

<p>A list of networks is specified that access is allowed from. In this example, the list of networks for both users is loaded from a separate file (/etc/metrika.xml) containing the &#39;networks&#39; substitution. Here is a fragment of it:</p>

<pre class='text-example'>
&lt;yandex>
	...
	&lt;networks>
		&lt;ip>::/64&lt;/ip>
		&lt;ip>93.158.111.111/26&lt;/ip>
		&lt;ip>2a02:6b8:0:1::/64&lt;/ip>
	...
	&lt;/networks>
&lt;/yandex>
</pre>

<p>We could have defined this list of networks directly in &#39;users.xml&#39;, or in a file in the &#39;users.d&#39; directory (for more information, see the section &quot;Configuration files&quot;).</p>

<p>The config includes comments explaining how to open access from everywhere.</p>

<p>For use in production, only specify IP elements (IP addresses and their masks), since using &#39;host&#39; and &#39;hoost_regexp&#39; might cause extra latency.</p>

<p>Next the user settings profile is specified (see the section &quot;Settings profiles&quot;). You can specify the default profile, &#39;default&#39;. The profile can have any name. You can specify the same profile for different users. The most important thing you can write in the settings profile is &#39;readonly&#39; set to 1, which provides read-only access.</p>

<p>After this, the quota is defined (see the section &quot;Quotas&quot;). You can specify the default quota, &#39;default&#39;. It is set in the config by default so that it only counts resource usage, but does not restrict it. The quota can have any name. You can specify the same quota for different users - in this case, resource usage is calculated for each user individually.</p>

</div>
<div class='island'>
<h1>Quotas</h1>
</div>
<div class='island'>

<p>Quotas allow you to limit resource usage over a period of time, or simply track the use of resources.
Quotas are set up in the user config. This is usually &#39;users.xml&#39;.</p>

<p>The system also has a feature for limiting the complexity of a single query (see the section &quot;Restrictions on query complexity&quot;).
In contrast to query complexity restrictions, quotas:
- place restrictions on a set of queries that can be run over a period of time, instead of limiting a single query.
- account for resources spent on all remote servers for distributed query processing.</p>

<p>Let&#39;s look at the section of the &#39;users.xml&#39; file that defines quotas.</p>

<pre class='text-example'>
&lt;!-- Quotas. -->
&lt;quotas>
	&lt;!-- Quota name. -->
	&lt;default>
		&lt;!-- Restrictions for a time period. You can set multiple time intervals with various restrictions. -->
		&lt;interval>
			&lt;!-- Length of time. -->
			&lt;duration>3600&lt;/duration>

			&lt;!-- No restrictions. Just collect data for the specified time interval. -->
			&lt;queries>0&lt;/queries>
			&lt;errors>0&lt;/errors>
			&lt;result_rows>0&lt;/result_rows>
			&lt;read_rows>0&lt;/read_rows>
			&lt;execution_time>0&lt;/execution_time>
		&lt;/interval>
	&lt;/default>
</pre>

<p>By default, the quota just tracks resource consumption for each hour, without limiting usage.</p>

<pre class='text-example'>
&lt;statbox>
	&lt;!-- Restrictions for a time period. You can set multiple time intervals with various restrictions. -->
	&lt;interval>
		&lt;!-- Length of time.-->
		&lt;duration>3600&lt;/duration>
		&lt;queries>1000&lt;/queries>
		&lt;errors>100&lt;/errors>
		&lt;result_rows>1000000000&lt;/result_rows>
		&lt;read_rows>100000000000&lt;/read_rows>
		&lt;execution_time>900&lt;/execution_time>
	&lt;/interval>
	&lt;interval>
		&lt;duration>86400&lt;/duration>
		&lt;queries>10000&lt;/queries>
		&lt;errors>1000&lt;/errors>
		&lt;result_rows>5000000000&lt;/result_rows>
		&lt;read_rows>500000000000&lt;/read_rows>
		&lt;execution_time>7200&lt;/execution_time>
	&lt;/interval>
&lt;/statbox>
</pre>

<p>For the &#39;statbox&#39; quota, restrictions are set for every hour and for every 24 hours (86,400 seconds). The time interval is counted starting from an implementation-defined fixed moment in time. In other words, the 24-hour interval doesn&#39;t necessarily begin at midnight.</p>

<p>When the interval ends, all collected values are cleared. For the next hour, the quota calculation starts over.</p>

<p>Let&#39;s examine the amounts that can be restricted:</p>

<p><b>queries</b> - The overall number of queries.
<b>errors</b> - The number of queries that threw exceptions.
<b>result_rows</b> - The total number of rows output in results.
<b>read_rows</b> - The total number of source rows retrieved from tables for running a query, on all remote servers.
<b>execution_time</b> - The total time of query execution, in seconds (wall time).</p>

<p>If the limit is exceeded for at least one time interval, an exception is thrown with a text about which restriction was exceeded, for which interval, and when the new interval begins (when queries can be sent again).</p>

<p>Quotas can use the &quot;quota key&quot; feature in order to report on resources for multiple keys independently. Here is an example of this:</p>

<pre class='text-example'> &lt;!-- For the global report builder. --> &lt;web_global> &lt;!-- keyed - the quota_key &quot;key&quot; is passed in the query parameter, and the quota is tracked separately for each key value. For example, you can pass a Metrica username as the key, so the quota will be counted separately for each username. Using keys makes sense only if quota_key is transmitted by the program, not by a user. You can also write &lt;keyed_by_ip /> so the IP address is used as the quota key. (But keep in mind that users can change the IPv6 address fairly easily.) --> &lt;keyed /> </pre>

<p>The quota is assigned to users in the &#39;users&#39; section of the config. See the section &quot;Access rights&quot;.</p>

<p>For distributed query processing, the accumulated amounts are stored on the requestor server. So if the user goes to another server, the quota there will &quot;start over&quot;.</p>

<p>When the server is restarted, quotas are reset.</p>

</div>


<div class='informer'>
<!-- Yandex.Metrica informer -->
<a href="https://metrika.yandex.ru/stat/?id=18343495&amp;from=informer"
target="_blank" rel="nofollow"><img src="https://bs.yandex.ru/informer/18343495/2_1_FFFFFFFF_EFEFEFFF_0_pageviews"
style="width:80px; height:31px; border:0;" alt="Yandex.Metrica" title="Yandex.Metrica: data for today (pageviews)" onclick="try{Ya.Metrika.informer({i:this,id:18343495,type:0,lang:'ru'});return false}catch(e){}"/></a>
<!-- /Yandex.Metrica informer -->
</div>

<script type='text/javascript'>

$('.show-example').each(function() {
    var link = $("<a class='show-hide-link'>Show example<\/a>");
    var example = $(this);
    example.before(link);
    link.click(function() {
        example.toggle(100);
        link.text('Example:');
    });
});


// Создаём содержание.

var contents = [];
var set_of_anchors = {};

// Триграмный индекс текстов anchor-ов. Используется, чтобы расставить ссылки на разделы внутри текста.
var trigram_to_anchor = {};
var anchor_to_element = {};

function getTrigrams(s) {
	s = s.toLowerCase();

	var res = [];
	if (s.length < 3) {
		return;
	}

	for (var i = 0; i < s.length - 2; ++i) {
		res.push(s.substring(i, i + 3));
	}

	return res;
}

$('h1, h2, h3, h4, h5, h6').each(function() {
    var elem = $(this);
    var text = elem.text().replace(/^\d+\.\s+/, '');
    var anchor = text;
    var margin = elem.prop('tagName').substring(1) - 1;

    if (elem.hasClass('not-for-contents')) {
        return;
    }

    /// Снимает неоднозначность

    if (set_of_anchors[anchor] === undefined) {
        set_of_anchors[anchor] = 0;
    }

    ++set_of_anchors[anchor];

    if (set_of_anchors[anchor] > 1) {
        anchor += set_of_anchors[anchor];
    }

	var trigrams = getTrigrams(anchor);
	for (var i in trigrams) {
		if (trigram_to_anchor[trigrams[i]] === undefined) {
			trigram_to_anchor[trigrams[i]] = [];
		}
		trigram_to_anchor[trigrams[i]].push(anchor);
	}

    elem.before($("<a href='#" + anchor + "' class='head-anchor' name='" + anchor + "'>⚓<\/a>"));

    contents.push("<a href='#" + anchor + "' class='contents-element' style='margin-left:" + margin + "em'>" + text + "<\/a><br \/>");
});

$('#contents').html(contents.join(''));


// Найти по триграмному индексу лучший anchor для текста.
function findBestAnchor(s) {
	s = s.toLowerCase();
	var trigrams = getTrigrams(s);
	var anchors_score = {};

	for (var i in trigrams) {
		if (trigram_to_anchor.hasOwnProperty(trigrams[i])) {
			for (var j in trigram_to_anchor[trigrams[i]]) {
				if (anchors_score[trigram_to_anchor[trigrams[i]][j]] === undefined) {
					anchors_score[trigram_to_anchor[trigrams[i]][j]] = 0;
				}
				anchors_score[trigram_to_anchor[trigrams[i]][j]] += 1.0 / Math.sqrt(trigram_to_anchor[trigrams[i]][j].length);
			}
		}
	}

	var anchors_matched = [];
	for (var name in anchors_score) {
		anchors_matched.push({ name : name, score : anchors_score[name] });
	}

	anchors_matched.sort(function(a, b) { return b.score - a.score; });
//	console.log(anchors_matched);
	return anchors_matched[0].name;
}


$('p').each(function() {
    var elem = $(this);
    var text = elem.text();

    var match = text.match(/(?:разделе?|sections?|see(?: the)?) "([^"]+?)"/i);
    if (match) {
		elem.html(elem.html().replace(/((?:разделе?|sections?|see(?: the)?) ")([^"]+?)\d?(")/i, '$1<a href="#' + findBestAnchor(match[1]) + '">$2</a>$3'));
    }
});

// Если человек пришёл по ссылке с именем раздела в хэше, а этого раздела не существует, то найдём лучший раздел по триграмному индексу.
if (location.hash.length > 1) {
	var queried = decodeURIComponent(location.hash.substring(1));
	if (!set_of_anchors.hasOwnProperty(queried)) {
		location.hash = "#" + findBestAnchor(queried);
	}
}


</script>

    </body>
</html>