formats.md 71.7 KB
Newer Older
I
Ivan Blinkov 已提交
1 2 3 4 5
---
toc_priority: 21
toc_title: Input and Output Formats
---

I
Ivan Blinkov 已提交
6
# Formats for Input and Output Data {#formats}
7

8
ClickHouse can accept and return data in various formats. A format supported for input can be used to parse the data provided to `INSERT`s, to perform `SELECT`s from a file-backed table such as File, URL or HDFS, or to read an external dictionary. A format supported for output can be used to arrange the
9
results of a `SELECT`, and to perform `INSERT`s into a file-backed table.
10

11
The supported formats are:
12

H
hcz 已提交
13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| Format                                                                                  | Input | Output |
|-----------------------------------------------------------------------------------------|-------|--------|
| [TabSeparated](#tabseparated)                                                           | ✔     | ✔      |
| [TabSeparatedRaw](#tabseparatedraw)                                                     | ✔     | ✔      |
| [TabSeparatedWithNames](#tabseparatedwithnames)                                         | ✔     | ✔      |
| [TabSeparatedWithNamesAndTypes](#tabseparatedwithnamesandtypes)                         | ✔     | ✔      |
| [Template](#format-template)                                                            | ✔     | ✔      |
| [TemplateIgnoreSpaces](#templateignorespaces)                                           | ✔     | ✗      |
| [CSV](#csv)                                                                             | ✔     | ✔      |
| [CSVWithNames](#csvwithnames)                                                           | ✔     | ✔      |
| [CustomSeparated](#format-customseparated)                                              | ✔     | ✔      |
| [Values](#data-format-values)                                                           | ✔     | ✔      |
| [Vertical](#vertical)                                                                   | ✗     | ✔      |
| [VerticalRaw](#verticalraw)                                                             | ✗     | ✔      |
| [JSON](#json)                                                                           | ✗     | ✔      |
F
filimonov 已提交
28
| [JSONAsString](#jsonasstring)                                                           | ✔     | ✗      |
H
hcz 已提交
29 30 31 32 33
| [JSONString](#jsonstring)                                                               | ✗     | ✔      |
| [JSONCompact](#jsoncompact)                                                             | ✗     | ✔      |
| [JSONCompactString](#jsoncompactstring)                                                 | ✗     | ✔      |
| [JSONEachRow](#jsoneachrow)                                                             | ✔     | ✔      |
| [JSONEachRowWithProgress](#jsoneachrowwithprogress)                                     | ✗     | ✔      |
34 35
| [JSONStringsEachRow](#jsonstringseachrow)                                               | ✔     | ✔      |
| [JSONStringsEachRowWithProgress](#jsonstringseachrowwithprogress)                       | ✗     | ✔      |
H
hcz 已提交
36 37 38 39 40 41 42 43 44 45 46
| [JSONCompactEachRow](#jsoncompacteachrow)                                               | ✔     | ✔      |
| [JSONCompactEachRowWithNamesAndTypes](#jsoncompacteachrowwithnamesandtypes)             | ✔     | ✔      |
| [JSONCompactStringEachRow](#jsoncompactstringeachrow)                                   | ✔     | ✔      |
| [JSONCompactStringEachRowWithNamesAndTypes](#jsoncompactstringeachrowwithnamesandtypes) | ✔     | ✔      |
| [TSKV](#tskv)                                                                           | ✔     | ✔      |
| [Pretty](#pretty)                                                                       | ✗     | ✔      |
| [PrettyCompact](#prettycompact)                                                         | ✗     | ✔      |
| [PrettyCompactMonoBlock](#prettycompactmonoblock)                                       | ✗     | ✔      |
| [PrettyNoEscapes](#prettynoescapes)                                                     | ✗     | ✔      |
| [PrettySpace](#prettyspace)                                                             | ✗     | ✔      |
| [Protobuf](#protobuf)                                                                   | ✔     | ✔      |
M
Mikhail Filimonov 已提交
47
| [ProtobufSingle](#protobufsingle)                                                       | ✔     | ✔      |
H
hcz 已提交
48 49 50 51 52 53 54 55 56 57 58 59
| [Avro](#data-format-avro)                                                               | ✔     | ✔      |
| [AvroConfluent](#data-format-avro-confluent)                                            | ✔     | ✗      |
| [Parquet](#data-format-parquet)                                                         | ✔     | ✔      |
| [Arrow](#data-format-arrow)                                                             | ✔     | ✔      |
| [ArrowStream](#data-format-arrow-stream)                                                | ✔     | ✔      |
| [ORC](#data-format-orc)                                                                 | ✔     | ✗      |
| [RowBinary](#rowbinary)                                                                 | ✔     | ✔      |
| [RowBinaryWithNamesAndTypes](#rowbinarywithnamesandtypes)                               | ✔     | ✔      |
| [Native](#native)                                                                       | ✔     | ✔      |
| [Null](#null)                                                                           | ✗     | ✔      |
| [XML](#xml)                                                                             | ✗     | ✔      |
| [CapnProto](#capnproto)                                                                 | ✔     | ✗      |
60
| [LineAsString](#lineasstring)                                                           | ✔     | ✗      |
61
| [Regexp](#data-format-regexp)                                                           | ✔     | ✗      |
A
annvsh 已提交
62
| [RawBLOB](#rawblob)                                                                     | ✔     | ✔      |
63

64
You can control some format processing parameters with the ClickHouse settings. For more information read the [Settings](../operations/settings/settings.md) section.
65

I
Ivan Blinkov 已提交
66
## TabSeparated {#tabseparated}
67

68
In TabSeparated format, data is written by row. Each row contains values separated by tabs. Each value is followed by a tab, except the last value in the row, which is followed by a line feed. Strictly Unix line feeds are assumed everywhere. The last row also must contain a line feed at the end. Values are written in text format, without enclosing quotation marks, and with special characters escaped.
69

I
Ivan Blinkov 已提交
70
This format is also available under the name `TSV`.
71

72
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’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.
I
Ivan Blinkov 已提交
73

74
The `TabSeparated` format supports outputting total values (when using WITH TOTALS) and extreme values (when ‘extremes’ 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:
I
Ivan Blinkov 已提交
75

76
``` sql
I
Ivan Blinkov 已提交
77
SELECT EventDate, count() AS c FROM test.hits GROUP BY EventDate WITH TOTALS ORDER BY EventDate FORMAT TabSeparated``
78 79
```

80
``` text
I
Ivan Blinkov 已提交
81 82 83 84 85 86 87 88
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

A
Alexey Milovidov 已提交
89
1970-01-01      8873898
90

I
Ivan Blinkov 已提交
91 92
2014-03-17      1031592
2014-03-23      1406958
93
```
I
Ivan Blinkov 已提交
94

95
### Data Formatting {#data-formatting}
I
Ivan Blinkov 已提交
96

97
Integer numbers are written in decimal form. Numbers can contain an extra “+” character at the beginning (ignored when parsing, and not recorded when formatting). Non-negative numbers can’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.
I
Ivan Blinkov 已提交
98

99
Floating-point numbers are written in decimal form. The dot is used as the decimal separator. Exponential entries are supported, as are ‘inf’, ‘+inf’, ‘-inf’, and ‘nan’. An entry of floating-point numbers may begin or end with a decimal point.
I
Ivan Blinkov 已提交
100 101 102 103
During formatting, accuracy may be lost on floating-point numbers.
During parsing, it is not strictly required to read the nearest machine-representable number.

Dates are written in YYYY-MM-DD format and parsed in the same format, but with any characters as separators.
104 105
Dates with times are written in the format `YYYY-MM-DD hh:mm:ss` and parsed 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 of them 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 parsing will select one of the two times.
I
Ivan Blinkov 已提交
106 107 108 109
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.

As an exception, parsing dates with times is also supported in Unix timestamp format, if it consists of exactly 10 decimal digits. The result is not time zone-dependent. The formats YYYY-MM-DD hh:mm:ss and NNNNNNNNNN are differentiated automatically.

110
Strings are output with backslash-escaped special characters. The following escape sequences are used for output: `\b`, `\f`, `\r`, `\n`, `\t`, `\0`, `\'`, `\\`. Parsing also supports the sequences `\a`, `\v`, and `\xHH` (hex escape sequences) and any `\c` sequences, where `c` is any character (these sequences are converted to `c`). Thus, reading data supports formats where a line feed can be written as `\n` or `\`, or as a line feed. For example, the string `Hello world` with a line feed between the words instead of space can be parsed in any of the following variations:
I
Ivan Blinkov 已提交
111

112
``` text
I
Ivan Blinkov 已提交
113
Hello\nworld
114

I
Ivan Blinkov 已提交
115 116 117 118 119 120 121 122 123 124
Hello\
world
```

The second variant is supported because MySQL uses it when writing tab-separated dumps.

The minimum set of characters that you need to escape when passing data in TabSeparated format: tab, line feed (LF) and backslash.

Only a small set of symbols are escaped. You can easily stumble onto a string value that your terminal will ruin in output.

125
Arrays are written as a list of comma-separated values in square brackets. Number items in the array are formatted as normally. `Date` and `DateTime` types are written in single quotes. Strings are written in single quotes with the same escaping rules as above.
I
Ivan Blinkov 已提交
126

127
[NULL](../sql-reference/syntax.md) is formatted as `\N`.
I
Ivan Blinkov 已提交
128

129
Each element of [Nested](../sql-reference/data-types/nested-data-structures/nested.md) structures is represented as array.
130 131 132

For example:

133
``` sql
134 135
CREATE TABLE nestedt
(
136
    `id` UInt8,
137
    `aux` Nested(
138
        a UInt8,
139 140 141 142 143
        b String
    )
)
ENGINE = TinyLog
```
144 145

``` sql
146 147
INSERT INTO nestedt Values ( 1, [1], ['a'])
```
148 149

``` sql
150 151
SELECT * FROM nestedt FORMAT TSV
```
152 153

``` text
154
1  [1]    ['a']
155 156
```

I
Ivan Blinkov 已提交
157
## TabSeparatedRaw {#tabseparatedraw}
I
Ivan Blinkov 已提交
158 159

Differs from `TabSeparated` format in that the rows are written without escaping.
H
hcz 已提交
160
When parsing with this format, tabs or linefeeds are not allowed in each field.
I
Ivan Blinkov 已提交
161 162 163

This format is also available under the name `TSVRaw`.

I
Ivan Blinkov 已提交
164
## TabSeparatedWithNames {#tabseparatedwithnames}
I
Ivan Blinkov 已提交
165 166

Differs from the `TabSeparated` format in that the column names are written in the first row.
167
During parsing, the first row is completely ignored. You can’t use column names to determine their position or to check their correctness.
I
Ivan Blinkov 已提交
168 169 170 171
(Support for parsing the header row may be added in the future.)

This format is also available under the name `TSVWithNames`.

I
Ivan Blinkov 已提交
172
## TabSeparatedWithNamesAndTypes {#tabseparatedwithnamesandtypes}
I
Ivan Blinkov 已提交
173 174 175 176 177 178

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.
During parsing, the first and second rows are completely ignored.

This format is also available under the name `TSVWithNamesAndTypes`.

I
Ivan Blinkov 已提交
179
## Template {#format-template}
A
Alexander Tokmakov 已提交
180

181
This format allows specifying a custom format string with placeholders for values with a specified escaping rule.
A
Alexander Tokmakov 已提交
182

183
It uses settings `format_template_resultset`, `format_template_row`, `format_template_rows_between_delimiter` and some settings of other formats (e.g. `output_format_json_quote_64bit_integers` when using `JSON` escaping, see further)
A
Alexander Tokmakov 已提交
184

A
Alexander Tokmakov 已提交
185
Setting `format_template_row` specifies path to file, which contains format string for rows with the following syntax:
A
Alexander Tokmakov 已提交
186

187
`delimiter_1${column_1:serializeAs_1}delimiter_2${column_2:serializeAs_2} ... delimiter_N`,
A
Alexander Tokmakov 已提交
188

189 190 191
where `delimiter_i` is a delimiter between values (`$` symbol can be escaped as `$$`),
`column_i` is a name or index of a column whose values are to be selected or inserted (if empty, then column will be skipped),
`serializeAs_i` is an escaping rule for the column values. The following escaping rules are supported:
192

193 194 195 196 197
-   `CSV`, `JSON`, `XML` (similarly to the formats of the same names)
-   `Escaped` (similarly to `TSV`)
-   `Quoted` (similarly to `Values`)
-   `Raw` (without escaping, similarly to `TSVRaw`)
-   `None` (no escaping rule, see further)
198

199
If an escaping rule is omitted, then `None` will be used. `XML` and `Raw` are suitable only for output.
200

201
So, for the following format string:
202

203
      `Search phrase: ${SearchPhrase:Quoted}, count: ${c:Escaped}, ad price: $$${price:JSON};`
204

205
the values of `SearchPhrase`, `c` and `price` columns, which are escaped as `Quoted`, `Escaped` and `JSON` will be printed (for select) or will be expected (for insert) between `Search phrase:`, `, count:`, `, ad price: $` and `;` delimiters respectively. For example:
A
Alexander Tokmakov 已提交
206

207
`Search phrase: 'bathroom interior design', count: 2166, ad price: $3;`
208

209
The `format_template_rows_between_delimiter` setting specifies delimiter between rows, which is printed (or expected) after every row except the last one (`\n` by default)
A
Alexander Tokmakov 已提交
210

211
Setting `format_template_resultset` specifies the path to file, which contains a format string for resultset. Format string for resultset has the same syntax as a format string for row and allows to specify a prefix, a suffix and a way to print some additional information. It contains the following placeholders instead of column names:
A
Alexander Tokmakov 已提交
212

213 214 215 216 217
-   `data` is the rows with data in `format_template_row` format, separated by `format_template_rows_between_delimiter`. This placeholder must be the first placeholder in the format string.
-   `totals` is the row with total values in `format_template_row` format (when using WITH TOTALS)
-   `min` is the row with minimum values in `format_template_row` format (when extremes are set to 1)
-   `max` is the row with maximum values in `format_template_row` format (when extremes are set to 1)
-   `rows` is the total number of output rows
A
Alexey Milovidov 已提交
218
-   `rows_before_limit` is the minimal number of rows there would have been without LIMIT. Output only if the query contains LIMIT. If the query contains GROUP BY, rows_before_limit_at_least is the exact number of rows there would have been without a LIMIT.
219 220 221
-   `time` is the request execution time in seconds
-   `rows_read` is the number of rows has been read
-   `bytes_read` is the number of bytes (uncompressed) has been read
222 223 224 225 226 227 228 229

The placeholders `data`, `totals`, `min` and `max` must not have escaping rule specified (or `None` must be specified explicitly). The remaining placeholders may have any escaping rule specified.
If the `format_template_resultset` setting is an empty string, `${data}` is used as default value.
For insert queries format allows skipping some columns or some fields if prefix or suffix (see example).

Select example:

``` sql
230
SELECT SearchPhrase, count() AS c FROM test.hits GROUP BY SearchPhrase ORDER BY c DESC LIMIT 5 FORMAT Template SETTINGS
A
Alexander Tokmakov 已提交
231 232
format_template_resultset = '/some/path/resultset.format', format_template_row = '/some/path/row.format', format_template_rows_between_delimiter = '\n    '
```
233

A
Alexander Tokmakov 已提交
234
`/some/path/resultset.format`:
235 236

``` text
A
Alexander Tokmakov 已提交
237
<!DOCTYPE HTML>
A
Alexander Tokmakov 已提交
238 239 240 241 242 243 244 245 246 247 248
<html> <head> <title>Search phrases</title> </head>
 <body>
  <table border="1"> <caption>Search phrases</caption>
    <tr> <th>Search phrase</th> <th>Count</th> </tr>
    ${data}
  </table>
  <table border="1"> <caption>Max</caption>
    ${max}
  </table>
  <b>Processed ${rows_read:XML} rows in ${time:XML} sec</b>
 </body>
A
Alexander Tokmakov 已提交
249
</html>
A
Alexander Tokmakov 已提交
250
```
251

A
Alexander Tokmakov 已提交
252
`/some/path/row.format`:
253 254

``` text
A
Alexander Tokmakov 已提交
255
<tr> <td>${0:XML}</td> <td>${1:XML}</td> </tr>
A
Alexander Tokmakov 已提交
256
```
257

A
Alexander Tokmakov 已提交
258
Result:
259 260

``` html
A
Alexander Tokmakov 已提交
261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279
<!DOCTYPE HTML>
<html> <head> <title>Search phrases</title> </head>
 <body>
  <table border="1"> <caption>Search phrases</caption>
    <tr> <th>Search phrase</th> <th>Count</th> </tr>
    <tr> <td></td> <td>8267016</td> </tr>
    <tr> <td>bathroom interior design</td> <td>2166</td> </tr>
    <tr> <td>yandex</td> <td>1655</td> </tr>
    <tr> <td>spring 2014 fashion</td> <td>1549</td> </tr>
    <tr> <td>freeform photos</td> <td>1480</td> </tr>
  </table>
  <table border="1"> <caption>Max</caption>
    <tr> <td></td> <td>8873898</td> </tr>
  </table>
  <b>Processed 3095973 rows in 0.1569913 sec</b>
 </body>
</html>
```

A
Alexander Tokmakov 已提交
280
Insert example:
281 282

``` text
A
Alexander Tokmakov 已提交
283 284 285 286
Some header
Page views: 5, User id: 4324182021466249494, Useless field: hello, Duration: 146, Sign: -1
Page views: 6, User id: 4324182021466249494, Useless field: world, Duration: 185, Sign: 1
Total rows: 2
A
Alexander Tokmakov 已提交
287
```
288 289

``` sql
290
INSERT INTO UserActivity FORMAT Template SETTINGS
A
Alexander Tokmakov 已提交
291 292
format_template_resultset = '/some/path/resultset.format', format_template_row = '/some/path/row.format'
```
293

A
Alexander Tokmakov 已提交
294
`/some/path/resultset.format`:
295 296

``` text
A
Alexander Tokmakov 已提交
297 298
Some header\n${data}\nTotal rows: ${:CSV}\n
```
299

A
Alexander Tokmakov 已提交
300
`/some/path/row.format`:
301 302

``` text
A
Alexander Tokmakov 已提交
303
Page views: ${PageViews:CSV}, User id: ${UserID:CSV}, Useless field: ${:CSV}, Duration: ${Duration:CSV}, Sign: ${Sign:CSV}
A
Alexander Tokmakov 已提交
304
```
305 306

`PageViews`, `UserID`, `Duration` and `Sign` inside placeholders are names of columns in the table. Values after `Useless field` in rows and after `\nTotal rows:` in suffix will be ignored.
A
Alexander Tokmakov 已提交
307
All delimiters in the input data must be strictly equal to delimiters in specified format strings.
308

I
Ivan Blinkov 已提交
309
## TemplateIgnoreSpaces {#templateignorespaces}
A
Alexander Tokmakov 已提交
310

A
Alexander Tokmakov 已提交
311
This format is suitable only for input.
312 313 314 315
Similar to `Template`, but skips whitespace characters between delimiters and values in the input stream. However, if format strings contain whitespace characters, these characters will be expected in the input stream. Also allows to specify empty placeholders (`${}` or `${:None}`) to split some delimiter into separate parts to ignore spaces between them. Such placeholders are used only for skipping whitespace characters.
It’s possible to read `JSON` using this format, if values of columns have the same order in all rows. For example, the following request can be used for inserting data from output example of format [JSON](#json):

``` sql
A
Alexander Tokmakov 已提交
316
INSERT INTO table_name FORMAT TemplateIgnoreSpaces SETTINGS
A
Alexander Tokmakov 已提交
317 318
format_template_resultset = '/some/path/resultset.format', format_template_row = '/some/path/row.format', format_template_rows_between_delimiter = ','
```
319

A
Alexander Tokmakov 已提交
320
`/some/path/resultset.format`:
321 322

``` text
A
Alexander Tokmakov 已提交
323 324
{${}"meta"${}:${:JSON},${}"data"${}:${}[${data}]${},${}"totals"${}:${:JSON},${}"extremes"${}:${:JSON},${}"rows"${}:${:JSON},${}"rows_before_limit_at_least"${}:${:JSON}${}}
```
325

A
Alexander Tokmakov 已提交
326
`/some/path/row.format`:
327 328

``` text
A
Alexander Tokmakov 已提交
329
{${}"SearchPhrase"${}:${}${phrase:JSON}${},${}"c"${}:${}${cnt:JSON}${}}
A
Alexander Tokmakov 已提交
330
```
A
Alexander Tokmakov 已提交
331

I
Ivan Blinkov 已提交
332
## TSKV {#tskv}
I
Ivan Blinkov 已提交
333 334 335

Similar to TabSeparated, but outputs a value in name=value format. Names are escaped the same way as in TabSeparated format, and the = symbol is also escaped.

336
``` text
I
Ivan Blinkov 已提交
337 338 339 340 341 342 343 344 345 346 347 348
SearchPhrase=   count()=8267016
SearchPhrase=bathroom interior design    count()=2166
SearchPhrase=yandex     count()=1655
SearchPhrase=2014 spring fashion    count()=1549
SearchPhrase=freeform photos       count()=1480
SearchPhrase=angelina jolie    count()=1245
SearchPhrase=omsk       count()=1112
SearchPhrase=photos of dog breeds    count()=1091
SearchPhrase=curtain designs        count()=1064
SearchPhrase=baku       count()=1000
```

349
[NULL](../sql-reference/syntax.md) is formatted as `\N`.
I
Ivan Blinkov 已提交
350 351 352 353 354

``` sql
SELECT * FROM t_null FORMAT TSKV
```

355
``` text
356
x=1    y=\N
I
Ivan Blinkov 已提交
357 358
```

A
alexey-milovidov 已提交
359
When there is a large number of small columns, this format is ineffective, and there is generally no reason to use it. Nevertheless, it is no worse than JSONEachRow in terms of efficiency.
I
Ivan Blinkov 已提交
360 361 362 363

Both data output and parsing are supported in this format. For parsing, any order is supported for the values of different columns. It is acceptable for some values to be omitted – they are treated as equal to their default values. In this case, zeros and blank rows are used as default values. Complex values that could be specified in the table are not supported as defaults.

Parsing allows the presence of the additional field `tskv` without the equal sign or a value. This field is ignored.
364

I
Ivan Blinkov 已提交
365
## CSV {#csv}
366 367 368

Comma Separated Values format ([RFC](https://tools.ietf.org/html/rfc4180)).

A
Alexey Milovidov 已提交
369
When formatting, rows are enclosed in double-quotes. A double quote inside a string is output as two double quotes in a row. There are no other rules for escaping characters. Date and date-time are enclosed in double-quotes. Numbers are output without quotes. Values are separated by a delimiter character, which is `,` by default. The delimiter character is defined in the setting [format_csv_delimiter](../operations/settings/settings.md#settings-format_csv_delimiter). Rows are separated using the Unix line feed (LF). Arrays are serialized in CSV as follows: first, the array is serialized to a string as in TabSeparated format, and then the resulting string is output to CSV in double-quotes. Tuples in CSV format are serialized as separate columns (that is, their nesting in the tuple is lost).
370

371
``` bash
372
$ clickhouse-client --format_csv_delimiter="|" --query="INSERT INTO test.csv FORMAT CSV" < data.csv
C
chertus 已提交
373 374
```

A
Alexey Milovidov 已提交
375
\*By default, the delimiter is `,`. See the [format_csv_delimiter](../operations/settings/settings.md#settings-format_csv_delimiter) setting for more information.
376

377 378
When parsing, all values can be parsed either with or without quotes. Both double and single quotes are supported. Rows can also be arranged without quotes. In this case, they are parsed up to the delimiter character or line feed (CR or LF). In violation of the RFC, when parsing rows without quotes, the leading and trailing spaces and tabs are ignored. For the line feed, Unix (LF), Windows (CR LF) and Mac OS Classic (CR LF) types are all supported.

379
Empty unquoted input values are replaced with default values for the respective columns, if
A
Alexey Milovidov 已提交
380
[input_format_defaults_for_omitted_fields](../operations/settings/settings.md#session_settings-input_format_defaults_for_omitted_fields)
381 382
is enabled.

A
Alexey Milovidov 已提交
383
`NULL` is formatted as `\N` or `NULL` or an empty unquoted string (see settings [input_format_csv_unquoted_null_literal_as_null](../operations/settings/settings.md#settings-input_format_csv_unquoted_null_literal_as_null) and [input_format_defaults_for_omitted_fields](../operations/settings/settings.md#session_settings-input_format_defaults_for_omitted_fields)).
384 385 386

The CSV format supports the output of totals and extremes the same way as `TabSeparated`.

387
## CSVWithNames {#csvwithnames}
388 389 390

Also prints the header row, similar to `TabSeparatedWithNames`.

I
Ivan Blinkov 已提交
391
## CustomSeparated {#format-customseparated}
A
Alexander Tokmakov 已提交
392 393 394 395

Similar to [Template](#format-template), but it prints or reads all columns and uses escaping rule from setting `format_custom_escaping_rule` and delimiters from settings `format_custom_field_delimiter`, `format_custom_row_before_delimiter`, `format_custom_row_after_delimiter`, `format_custom_row_between_delimiter`, `format_custom_result_before_delimiter` and `format_custom_result_after_delimiter`, not from format strings.
There is also `CustomSeparatedIgnoreSpaces` format, which is similar to `TemplateIgnoreSpaces`.

I
Ivan Blinkov 已提交
396
## JSON {#json}
397

398
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’t a LIMIT. Example:
399

400
``` sql
401 402 403
SELECT SearchPhrase, count() AS c FROM test.hits GROUP BY SearchPhrase WITH TOTALS ORDER BY c DESC LIMIT 5 FORMAT JSON
```

404
``` json
405 406 407 408
{
        "meta":
        [
                {
H
hcz 已提交
409
                        "name": "'hello'",
410 411 412
                        "type": "String"
                },
                {
H
hcz 已提交
413
                        "name": "multiply(42, number)",
414
                        "type": "UInt64"
H
hcz 已提交
415 416 417 418
                },
                {
                        "name": "range(5)",
                        "type": "Array(UInt8)"
419 420 421 422 423 424
                }
        ],

        "data":
        [
                {
H
hcz 已提交
425 426 427
                        "'hello'": "hello",
                        "multiply(42, number)": "0",
                        "range(5)": [0,1,2,3,4]
428 429
                },
                {
H
hcz 已提交
430 431 432
                        "'hello'": "hello",
                        "multiply(42, number)": "42",
                        "range(5)": [0,1,2,3,4]
433 434
                },
                {
H
hcz 已提交
435 436 437
                        "'hello'": "hello",
                        "multiply(42, number)": "84",
                        "range(5)": [0,1,2,3,4]
438 439 440
                }
        ],

H
hcz 已提交
441
        "rows": 3,
442

H
hcz 已提交
443
        "rows_before_limit_at_least": 3
444 445 446
}
```

A
Alexey Milovidov 已提交
447
The JSON is compatible with JavaScript. To ensure this, some characters are additionally escaped: the slash `/` is escaped as `\/`; alternative line breaks `U+2028` and `U+2029`, which break some browsers, are escaped as `\uXXXX`. ASCII control characters are escaped: backspace, form feed, line feed, carriage return, and horizontal tab are replaced with `\b`, `\f`, `\n`, `\r`, `\t` , as well as the remaining bytes in the 00-1F range using `\uXXXX` sequences. Invalid UTF-8 sequences are changed to the replacement character � so the output text will consist of valid UTF-8 sequences. For compatibility with JavaScript, Int64 and UInt64 integers are enclosed in double-quotes by default. To remove the quotes, you can set the configuration parameter [output_format_json_quote_64bit_integers](../operations/settings/settings.md#session_settings-output_format_json_quote_64bit_integers) to 0.
448 449 450 451

`rows` – The total number of output rows.

`rows_before_limit_at_least` The minimal number of rows there would have been without LIMIT. Output only if the query contains LIMIT.
A
Alexey Milovidov 已提交
452
If the query contains GROUP BY, rows_before_limit_at_least is the exact number of rows there would have been without a LIMIT.
453 454 455

`totals` – Total values (when using WITH TOTALS).

456
`extremes` – Extreme values (when extremes are set to 1).
457 458

This format is only appropriate for outputting a query result, but not for parsing (retrieving data to insert in a table).
459

A
Alexey Milovidov 已提交
460
ClickHouse supports [NULL](../sql-reference/syntax.md), which is displayed as `null` in the JSON output. To enable `+nan`, `-nan`, `+inf`, `-inf` values in output, set the [output_format_json_quote_denormals](../operations/settings/settings.md#settings-output_format_json_quote_denormals) to 1.
461

D
Dmitriy 已提交
462 463
**See Also**

D
Dmitriy 已提交
464 465
-   [JSONEachRow](#jsoneachrow) format
-   [output_format_json_array_of_rows](../operations/settings/settings.md#output-format-json-array-of-rows) setting
466

H
hcz 已提交
467
## JSONString {#jsonstring}
468

469
Differs from JSON only in that data fields are output in strings, not in typed JSON values.
470 471 472

Example:

H
hcz 已提交
473
```json
474 475 476 477
{
        "meta":
        [
                {
H
hcz 已提交
478
                        "name": "'hello'",
479 480 481
                        "type": "String"
                },
                {
H
hcz 已提交
482
                        "name": "multiply(42, number)",
483
                        "type": "UInt64"
H
hcz 已提交
484 485 486 487
                },
                {
                        "name": "range(5)",
                        "type": "Array(UInt8)"
488 489 490 491 492
                }
        ],

        "data":
        [
H
hcz 已提交
493 494 495 496 497 498 499 500 501 502 503 504 505 506 507
                {
                        "'hello'": "hello",
                        "multiply(42, number)": "0",
                        "range(5)": "[0,1,2,3,4]"
                },
                {
                        "'hello'": "hello",
                        "multiply(42, number)": "42",
                        "range(5)": "[0,1,2,3,4]"
                },
                {
                        "'hello'": "hello",
                        "multiply(42, number)": "84",
                        "range(5)": "[0,1,2,3,4]"
                }
508 509
        ],

H
hcz 已提交
510 511 512 513 514 515
        "rows": 3,

        "rows_before_limit_at_least": 3
}
```

F
filimonov 已提交
516 517
## JSONAsString {#jsonasstring}

D
Dmitriy 已提交
518
In this format, a single JSON object is interpreted as a single value. If the input has several JSON objects (comma separated) they will be interpreted as separate rows.
F
filimonov 已提交
519

D
Dmitriy 已提交
520
This format can only be parsed for table with a single field of type [String](../sql-reference/data-types/string.md). The remaining columns must be set to [DEFAULT](../sql-reference/statements/create/table.md#default) or [MATERIALIZED](../sql-reference/statements/create/table.md#materialized), or omitted. Once you collect whole JSON object to string you can use [JSON functions](../sql-reference/functions/json-functions.md) to process it.
F
filimonov 已提交
521 522 523 524 525 526 527 528

**Example**

Query:

``` sql
DROP TABLE IF EXISTS json_as_string;
CREATE TABLE json_as_string (json String) ENGINE = Memory;
D
Dmitriy 已提交
529
INSERT INTO json_as_string (json) FORMAT JSONAsString {"foo":{"bar":{"x":"y"},"baz":1}},{},{"any json stucture":1}
F
filimonov 已提交
530 531 532 533 534 535 536 537 538 539 540 541 542
SELECT * FROM json_as_string;
```

Result:

``` text
┌─json──────────────────────────────┐
│ {"foo":{"bar":{"x":"y"},"baz":1}} │
│ {}                                │
│ {"any json stucture":1}           │
└───────────────────────────────────┘
```

H
hcz 已提交
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
## JSONCompact {#jsoncompact}
## JSONCompactString {#jsoncompactstring}

Differs from JSON only in that data rows are output in arrays, not in objects.

Example:

``` json
// JSONCompact
{
        "meta":
        [
                {
                        "name": "'hello'",
                        "type": "String"
                },
                {
                        "name": "multiply(42, number)",
                        "type": "UInt64"
                },
                {
                        "name": "range(5)",
                        "type": "Array(UInt8)"
                }
        ],
568

H
hcz 已提交
569 570 571 572 573 574
        "data":
        [
                ["hello", "0", [0,1,2,3,4]],
                ["hello", "42", [0,1,2,3,4]],
                ["hello", "84", [0,1,2,3,4]]
        ],
575

H
hcz 已提交
576
        "rows": 3,
577

H
hcz 已提交
578
        "rows_before_limit_at_least": 3
579 580 581
}
```

H
hcz 已提交
582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599
```json
// JSONCompactString
{
        "meta":
        [
                {
                        "name": "'hello'",
                        "type": "String"
                },
                {
                        "name": "multiply(42, number)",
                        "type": "UInt64"
                },
                {
                        "name": "range(5)",
                        "type": "Array(UInt8)"
                }
        ],
600

H
hcz 已提交
601 602 603 604 605 606
        "data":
        [
                ["hello", "0", "[0,1,2,3,4]"],
                ["hello", "42", "[0,1,2,3,4]"],
                ["hello", "84", "[0,1,2,3,4]"]
        ],
H
hcz 已提交
607

H
hcz 已提交
608
        "rows": 3,
H
hcz 已提交
609

H
hcz 已提交
610 611 612
        "rows_before_limit_at_least": 3
}
```
H
hcz 已提交
613

I
Ivan Blinkov 已提交
614
## JSONEachRow {#jsoneachrow}
615
## JSONStringsEachRow {#jsonstringseachrow}
H
hcz 已提交
616
## JSONCompactEachRow {#jsoncompacteachrow}
H
hcz 已提交
617
## JSONCompactStringEachRow {#jsoncompactstringeachrow}
618

H
hcz 已提交
619
When using these formats, ClickHouse outputs rows as separated, newline-delimited JSON values, but the data as a whole is not valid JSON.
620

621
``` json
H
hcz 已提交
622 623
{"some_int":42,"some_str":"hello","some_tuple":[1,"a"]} // JSONEachRow
[42,"hello",[1,"a"]] // JSONCompactEachRow
H
hcz 已提交
624
["42","hello","(2,'a')"] // JSONCompactStringsEachRow
625 626
```

H
hcz 已提交
627
When inserting the data, you should provide a separate JSON value for each row.
628

H
hcz 已提交
629
## JSONEachRowWithProgress {#jsoneachrowwithprogress}
630
## JSONStringsEachRowWithProgress {#jsonstringseachrowwithprogress}
H
hcz 已提交
631

632
Differs from `JSONEachRow`/`JSONStringsEachRow` in that ClickHouse will also yield progress information as JSON values.
H
hcz 已提交
633 634 635 636 637 638 639 640 641 642 643

```json
{"row":{"'hello'":"hello","multiply(42, number)":"0","range(5)":[0,1,2,3,4]}}
{"row":{"'hello'":"hello","multiply(42, number)":"42","range(5)":[0,1,2,3,4]}}
{"row":{"'hello'":"hello","multiply(42, number)":"84","range(5)":[0,1,2,3,4]}}
{"progress":{"read_rows":"3","read_bytes":"24","written_rows":"0","written_bytes":"0","total_rows_to_read":"3"}}
```

## JSONCompactEachRowWithNamesAndTypes {#jsoncompacteachrowwithnamesandtypes}
## JSONCompactStringEachRowWithNamesAndTypes {#jsoncompactstringeachrowwithnamesandtypes}

644
Differs from `JSONCompactEachRow`/`JSONCompactStringEachRow` in that the column names and types are written as the first two rows.
H
hcz 已提交
645 646 647 648 649 650 651 652 653

```json
["'hello'", "multiply(42, number)", "range(5)"]
["String", "UInt64", "Array(UInt8)"]
["hello", "0", [0,1,2,3,4]]
["hello", "42", [0,1,2,3,4]]
["hello", "84", [0,1,2,3,4]]
```

654
### Inserting Data {#inserting-data}
655

656
``` sql
657 658 659 660 661
INSERT INTO UserActivity FORMAT JSONEachRow {"PageViews":5, "UserID":"4324182021466249494", "Duration":146,"Sign":-1} {"UserID":"4324182021466249494","PageViews":6,"Duration":185,"Sign":1}
```

ClickHouse allows:

662 663
-   Any order of key-value pairs in the object.
-   Omitting some values.
664

665
ClickHouse ignores spaces between elements and commas after the objects. You can pass all the objects in one line. You don’t have to separate them with line breaks.
666

667
**Omitted values processing**
668

669
ClickHouse substitutes omitted values with the default values for the corresponding [data types](../sql-reference/data-types/index.md).
670

A
Alexey Milovidov 已提交
671
If `DEFAULT expr` is specified, ClickHouse uses different substitution rules depending on the [input_format_defaults_for_omitted_fields](../operations/settings/settings.md#session_settings-input_format_defaults_for_omitted_fields) setting.
672

673
Consider the following table:
674

675
``` sql
676 677 678 679 680 681 682
CREATE TABLE IF NOT EXISTS example_table
(
    x UInt32,
    a DEFAULT x * 2
) ENGINE = Memory;
```

683 684
-   If `input_format_defaults_for_omitted_fields = 0`, then the default value for `x` and `a` equals `0` (as the default value for the `UInt32` data type).
-   If `input_format_defaults_for_omitted_fields = 1`, then the default value for `x` equals `0`, but the default value of `a` equals `x * 2`.
685

686 687
!!! note "Warning"
    When inserting data with `insert_sample_with_metadata = 1`, ClickHouse consumes more computational resources, compared to insertion with `insert_sample_with_metadata = 0`.
688

689
### Selecting Data {#selecting-data}
690

691
Consider the `UserActivity` table as an example:
692

693
``` text
694 695 696 697 698 699 700 701
┌──────────────UserID─┬─PageViews─┬─Duration─┬─Sign─┐
│ 4324182021466249494 │         5 │      146 │   -1 │
│ 4324182021466249494 │         6 │      185 │    1 │
└─────────────────────┴───────────┴──────────┴──────┘
```

The query `SELECT * FROM UserActivity FORMAT JSONEachRow` returns:

702
``` text
703 704 705 706 707 708 709
{"UserID":"4324182021466249494","PageViews":5,"Duration":146,"Sign":-1}
{"UserID":"4324182021466249494","PageViews":6,"Duration":185,"Sign":1}
```

Unlike the [JSON](#json) format, there is no substitution of invalid UTF-8 sequences. Values are escaped in the same way as for `JSON`.

!!! note "Note"
710
    Any set of bytes can be output in the strings. Use the `JSONEachRow` format if you are sure that the data in the table can be formatted as JSON without losing any information.
711

I
Ivan Blinkov 已提交
712
### Usage of Nested Structures {#jsoneachrow-nested}
713

A
Alexey Milovidov 已提交
714
If you have a table with [Nested](../sql-reference/data-types/nested-data-structures/nested.md) data type columns, you can insert JSON data with the same structure. Enable this feature with the [input_format_import_nested_json](../operations/settings/settings.md#settings-input_format_import_nested_json) setting.
715 716 717

For example, consider the following table:

718
``` sql
719 720 721
CREATE TABLE json_each_row_nested (n Nested (s String, i Int32) ) ENGINE = Memory
```

722
As you can see in the `Nested` data type description, ClickHouse treats each component of the nested structure as a separate column (`n.s` and `n.i` for our table). You can insert data in the following way:
723

724
``` sql
725 726 727
INSERT INTO json_each_row_nested FORMAT JSONEachRow {"n.s": ["abc", "def"], "n.i": [1, 23]}
```

A
Alexey Milovidov 已提交
728
To insert data as a hierarchical JSON object, set [input_format_import_nested_json=1](../operations/settings/settings.md#settings-input_format_import_nested_json).
729

730
``` json
731 732 733 734 735 736 737 738
{
    "n": {
        "s": ["abc", "def"],
        "i": [1, 23]
    }
}
```

739
Without this setting, ClickHouse throws an exception.
740

741
``` sql
742 743
SELECT name, value FROM system.settings WHERE name = 'input_format_import_nested_json'
```
744 745

``` text
746 747 748 749
┌─name────────────────────────────┬─value─┐
│ input_format_import_nested_json │ 0     │
└─────────────────────────────────┴───────┘
```
750 751

``` sql
752 753
INSERT INTO json_each_row_nested FORMAT JSONEachRow {"n": {"s": ["abc", "def"], "i": [1, 23]}}
```
754 755

``` text
756 757
Code: 117. DB::Exception: Unknown field found while parsing JSONEachRow format: n: (at row 1)
```
758 759

``` sql
760 761 762 763
SET input_format_import_nested_json=1
INSERT INTO json_each_row_nested FORMAT JSONEachRow {"n": {"s": ["abc", "def"], "i": [1, 23]}}
SELECT * FROM json_each_row_nested
```
764 765

``` text
766 767 768 769 770
┌─n.s───────────┬─n.i────┐
│ ['abc','def'] │ [1,23] │
└───────────────┴────────┘
```

I
Ivan Blinkov 已提交
771
## Native {#native}
772

773
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 “columnar” – it doesn’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.
774

775
You can use this format to quickly generate dumps that can only be read by the ClickHouse DBMS. It doesn’t make sense to work with this format yourself.
776

I
Ivan Blinkov 已提交
777
## Null {#null}
778

779
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 performance testing.
780 781
Obviously, this format is only appropriate for output, not for parsing.

I
Ivan Blinkov 已提交
782
## Pretty {#pretty}
783

784
Outputs data as Unicode-art tables, also using ANSI-escape sequences for setting colours in the terminal.
785 786
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).
787

788
[NULL](../sql-reference/syntax.md) is output as `ᴺᵁᴸᴸ`.
789

790 791
Example (shown for the [PrettyCompact](#prettycompact) format):

792
``` sql
793 794 795
SELECT * FROM t_null
```

796
``` text
797 798 799 800 801
┌─x─┬────y─┐
│ 1 │ ᴺᵁᴸᴸ │
└───┴──────┘
```

802
Rows are not escaped in Pretty\* formats. Example is shown for the [PrettyCompact](#prettycompact) format:
803

804
``` sql
805 806 807
SELECT 'String with \'quotes\' and \t character' AS Escaping_test
```

808
``` text
809
┌─Escaping_test────────────────────────┐
810
│ String with 'quotes' and      character │
811 812 813
└──────────────────────────────────────┘
```

814
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 “Showed first 10 000” is printed.
815 816
This format is only appropriate for outputting a query result, but not for parsing (retrieving data to insert in a table).

817
The Pretty format supports outputting total values (when using WITH TOTALS) and extremes (when ‘extremes’ 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](#prettycompact) format):
818

819
``` sql
820 821 822
SELECT EventDate, count() AS c FROM test.hits GROUP BY EventDate WITH TOTALS ORDER BY EventDate FORMAT PrettyCompact
```

823
``` text
824 825 826 827 828 829 830 831 832 833 834 835
┌──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─┐
A
Alexey Milovidov 已提交
836
│ 1970-01-01 │ 8873898 │
837 838 839 840 841 842 843 844 845
└────────────┴─────────┘

Extremes:
┌──EventDate─┬───────c─┐
│ 2014-03-17 │ 1031592 │
│ 2014-03-23 │ 1406958 │
└────────────┴─────────┘
```

I
Ivan Blinkov 已提交
846
## PrettyCompact {#prettycompact}
847

848
Differs from [Pretty](#pretty) in that the grid is drawn between rows and the result is more compact.
849 850
This format is used by default in the command-line client in interactive mode.

I
Ivan Blinkov 已提交
851
## PrettyCompactMonoBlock {#prettycompactmonoblock}
852

853
Differs from [PrettyCompact](#prettycompact) in that up to 10,000 rows are buffered, then output as a single table, not by blocks.
854

I
Ivan Blinkov 已提交
855
## PrettyNoEscapes {#prettynoescapes}
856

857
Differs from Pretty in that ANSI-escape sequences aren’t used. This is necessary for displaying this format in a browser, as well as for using the ‘watch’ command-line utility.
858 859 860

Example:

861
``` bash
862
$ watch -n1 "clickhouse-client --query='SELECT event, value FROM system.events FORMAT PrettyCompactNoEscapes'"
863 864 865 866
```

You can use the HTTP interface for displaying in the browser.

867
### PrettyCompactNoEscapes {#prettycompactnoescapes}
868 869 870

The same as the previous setting.

871
### PrettySpaceNoEscapes {#prettyspacenoescapes}
872 873 874

The same as the previous setting.

I
Ivan Blinkov 已提交
875
## PrettySpace {#prettyspace}
876

877
Differs from [PrettyCompact](#prettycompact) in that whitespace (space characters) is used instead of the grid.
878

I
Ivan Blinkov 已提交
879
## RowBinary {#rowbinary}
880 881

Formats and parses data by row in binary format. Rows and values are listed consecutively, without separators.
882
This format is less efficient than the Native format since it is row-based.
883

884
Integers use fixed-length little-endian representation. For example, UInt64 uses 8 bytes.
885 886 887 888 889 890 891
DateTime is represented as UInt32 containing the Unix timestamp as the value.
Date is represented as a UInt16 object that contains the number of days since 1970-01-01 as the value.
String is represented as a varint length (unsigned [LEB128](https://en.wikipedia.org/wiki/LEB128)), followed by the bytes of the string.
FixedString is represented simply as a sequence of bytes.

Array is represented as a varint length (unsigned [LEB128](https://en.wikipedia.org/wiki/LEB128)), followed by successive elements of the array.

892
For [NULL](../sql-reference/syntax.md#null-literal) support, an additional byte containing 1 or 0 is added before each [Nullable](../sql-reference/data-types/nullable.md) value. If 1, then the value is `NULL` and this byte is interpreted as a separate value. If 0, the value after the byte is not `NULL`.
893

I
Ivan Blinkov 已提交
894
## RowBinaryWithNamesAndTypes {#rowbinarywithnamesandtypes}
895 896

Similar to [RowBinary](#rowbinary), but with added header:
D
Denis Zhuravlev 已提交
897

898 899 900
-   [LEB128](https://en.wikipedia.org/wiki/LEB128)-encoded number of columns (N)
-   N `String`s specifying column names
-   N `String`s specifying column types
901

I
Ivan Blinkov 已提交
902
## Values {#data-format-values}
903

904
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 a 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](#tabseparated) format. During formatting, extra spaces aren’t inserted, but during parsing, they are allowed and skipped (except for spaces inside array values, which are not allowed). [NULL](../sql-reference/syntax.md) is represented as `NULL`.
905 906 907 908 909

The minimum set of characters that you need to escape when passing data in Values ​​format: single quotes and backslashes.

This is the format that is used in `INSERT INTO t VALUES ...`, but you can also use it for formatting query results.

A
Alexey Milovidov 已提交
910
See also: [input_format_values_interpret_expressions](../operations/settings/settings.md#settings-input_format_values_interpret_expressions) and [input_format_values_deduce_templates_of_expressions](../operations/settings/settings.md#settings-input_format_values_deduce_templates_of_expressions) settings.
A
Alexander Tokmakov 已提交
911

I
Ivan Blinkov 已提交
912
## Vertical {#vertical}
913

914
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.
915

916
[NULL](../sql-reference/syntax.md) is output as `ᴺᵁᴸᴸ`.
917 918 919

Example:

920
``` sql
921 922 923
SELECT * FROM t_null FORMAT Vertical
```

924
``` text
925 926 927 928 929
Row 1:
──────
x: 1
y: ᴺᵁᴸᴸ
```
930

931
Rows are not escaped in Vertical format:
932

933
``` sql
934
SELECT 'string with \'quotes\' and \t with some special \n characters' AS test FORMAT Vertical
935 936
```

937
``` text
938 939
Row 1:
──────
940
test: string with 'quotes' and      with some special
941 942 943
 characters
```

944
This format is only appropriate for outputting a query result, but not for parsing (retrieving data to insert in a table).
945

I
Ivan Blinkov 已提交
946
## VerticalRaw {#verticalraw}
947 948 949

Similar to [Vertical](#vertical), but with escaping disabled. This format is only suitable for outputting query results, not for parsing (receiving data and inserting it in the table).

I
Ivan Blinkov 已提交
950
## XML {#xml}
951 952 953

XML format is suitable only for output, not for parsing. Example:

954
``` xml
955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982
<?xml version='1.0' encoding='UTF-8' ?>
<result>
        <meta>
                <columns>
                        <column>
                                <name>SearchPhrase</name>
                                <type>String</type>
                        </column>
                        <column>
                                <name>count()</name>
                                <type>UInt64</type>
                        </column>
                </columns>
        </meta>
        <data>
                <row>
                        <SearchPhrase></SearchPhrase>
                        <field>8267016</field>
                </row>
                <row>
                        <SearchPhrase>bathroom interior design</SearchPhrase>
                        <field>2166</field>
                </row>
                <row>
                        <SearchPhrase>yandex</SearchPhrase>
                        <field>1655</field>
                </row>
                <row>
983
                        <SearchPhrase>2014 spring fashion</SearchPhrase>
984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002
                        <field>1549</field>
                </row>
                <row>
                        <SearchPhrase>freeform photos</SearchPhrase>
                        <field>1480</field>
                </row>
                <row>
                        <SearchPhrase>angelina jolie</SearchPhrase>
                        <field>1245</field>
                </row>
                <row>
                        <SearchPhrase>omsk</SearchPhrase>
                        <field>1112</field>
                </row>
                <row>
                        <SearchPhrase>photos of dog breeds</SearchPhrase>
                        <field>1091</field>
                </row>
                <row>
1003
                        <SearchPhrase>curtain designs</SearchPhrase>
1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015
                        <field>1064</field>
                </row>
                <row>
                        <SearchPhrase>baku</SearchPhrase>
                        <field>1000</field>
                </row>
        </data>
        <rows>10</rows>
        <rows_before_limit_at_least>141137</rows_before_limit_at_least>
</result>
```

1016
If the column name does not have an acceptable format, just ‘field’ is used as the element name. In general, the XML structure follows the JSON structure.
1017 1018 1019 1020
Just as for JSON, invalid UTF-8 sequences are changed to the replacement character � so the output text will consist of valid UTF-8 sequences.

In string values, the characters `<` and `&` are escaped as `<` and `&`.

1021
Arrays are output as `<array><elem>Hello</elem><elem>World</elem>...</array>`,and tuples as `<tuple><elem>Hello</elem><elem>World</elem>...</tuple>`.
I
Ivan Blinkov 已提交
1022

I
Ivan Blinkov 已提交
1023
## CapnProto {#capnproto}
I
Ivan Blinkov 已提交
1024

1025
Cap’n Proto is a binary message format similar to Protocol Buffers and Thrift, but not like JSON or MessagePack.
I
Ivan Blinkov 已提交
1026

1027
Cap’n Proto messages are strictly typed and not self-describing, meaning they need an external schema description. The schema is applied on the fly and cached for each query.
I
Ivan Blinkov 已提交
1028

1029
``` bash
1030
$ cat capnproto_messages.bin | clickhouse-client --query "INSERT INTO test.hits FORMAT CapnProto SETTINGS format_schema='schema:Message'"
I
Ivan Blinkov 已提交
1031 1032 1033 1034
```

Where `schema.capnp` looks like this:

1035
``` capnp
I
Ivan Blinkov 已提交
1036 1037 1038 1039 1040 1041
struct Message {
  SearchPhrase @0 :Text;
  c @1 :Uint64;
}
```

1042
Deserialization is effective and usually doesn’t increase the system load.
I
Ivan Blinkov 已提交
1043

1044 1045
See also [Format Schema](#formatschema).

I
Ivan Blinkov 已提交
1046
## Protobuf {#protobuf}
1047 1048 1049 1050

Protobuf - is a [Protocol Buffers](https://developers.google.com/protocol-buffers/) format.

This format requires an external format schema. The schema is cached between queries.
1051 1052
ClickHouse supports both `proto2` and `proto3` syntaxes. Repeated/optional/required fields are supported.

1053 1054
Usage examples:

1055
``` sql
1056 1057 1058
SELECT * FROM test.table FORMAT Protobuf SETTINGS format_schema = 'schemafile:MessageType'
```

1059
``` bash
1060 1061 1062
cat protobuf_messages.bin | clickhouse-client --query "INSERT INTO test.table FORMAT Protobuf SETTINGS format_schema='schemafile:MessageType'"
```

1063
where the file `schemafile.proto` looks like this:
1064

1065
``` capnp
1066 1067 1068 1069 1070 1071 1072 1073 1074 1075
syntax = "proto3";

message MessageType {
  string name = 1;
  string surname = 2;
  uint32 birthDate = 3;
  repeated string phoneNumbers = 4;
};
```

1076
To find the correspondence between table columns and fields of Protocol Buffers’ message type ClickHouse compares their names.
1077
This comparison is case-insensitive and the characters `_` (underscore) and `.` (dot) are considered as equal.
1078
If types of a column and a field of Protocol Buffers’ message are different the necessary conversion is applied.
1079 1080 1081

Nested messages are supported. For example, for the field `z` in the following message type

1082
``` capnp
1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094
message MessageType {
  message XType {
    message YType {
      int32 z;
    };
    repeated YType y;
  };
  XType x;
};
```

ClickHouse tries to find a column named `x.y.z` (or `x_y_z` or `X.y_Z` and so on).
1095
Nested messages are suitable to input or output a [nested data structures](../sql-reference/data-types/nested-data-structures/nested.md).
1096

1097
Default values defined in a protobuf schema like this
1098

1099
``` capnp
1100 1101
syntax = "proto2";

1102 1103 1104 1105 1106
message MessageType {
  optional int32 result_per_page = 3 [default = 10];
}
```

1107
are not applied; the [table defaults](../sql-reference/statements/create/table.md#create-default-values) are used instead of them.
1108

1109 1110 1111 1112
ClickHouse inputs and outputs protobuf messages in the `length-delimited` format.
It means before every message should be written its length as a [varint](https://developers.google.com/protocol-buffers/docs/encoding#varints).
See also [how to read/write length-delimited protobuf messages in popular languages](https://cwiki.apache.org/confluence/display/GEODE/Delimiting+Protobuf+Messages).

M
Mikhail Filimonov 已提交
1113 1114 1115 1116
## ProtobufSingle {#protobufsingle}

Same as [Protobuf](#protobuf) but for storing/parsing single Protobuf message without length delimiters.

I
Ivan Blinkov 已提交
1117
## Avro {#data-format-avro}
A
Andrew Onyshchuk 已提交
1118

H
hcz 已提交
1119
[Apache Avro](https://avro.apache.org/) is a row-oriented data serialization framework developed within Apache’s Hadoop project.
A
Andrew Onyshchuk 已提交
1120

H
hcz 已提交
1121
ClickHouse Avro format supports reading and writing [Avro data files](https://avro.apache.org/docs/current/spec.html#Object+Container+Files).
A
Andrew Onyshchuk 已提交
1122

1123
### Data Types Matching {#data_types-matching}
A
Andrew Onyshchuk 已提交
1124

1125
The table below shows supported data types and how they match ClickHouse [data types](../sql-reference/data-types/index.md) in `INSERT` and `SELECT` queries.
A
Andrew Onyshchuk 已提交
1126

1127 1128
| Avro data type `INSERT`                     | ClickHouse data type                                                                                                  | Avro data type `SELECT`      |
|---------------------------------------------|-----------------------------------------------------------------------------------------------------------------------|------------------------------|
1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141
| `boolean`, `int`, `long`, `float`, `double` | [Int(8\|16\|32)](../sql-reference/data-types/int-uint.md), [UInt(8\|16\|32)](../sql-reference/data-types/int-uint.md) | `int`                        |
| `boolean`, `int`, `long`, `float`, `double` | [Int64](../sql-reference/data-types/int-uint.md), [UInt64](../sql-reference/data-types/int-uint.md)                   | `long`                       |
| `boolean`, `int`, `long`, `float`, `double` | [Float32](../sql-reference/data-types/float.md)                                                                       | `float`                      |
| `boolean`, `int`, `long`, `float`, `double` | [Float64](../sql-reference/data-types/float.md)                                                                       | `double`                     |
| `bytes`, `string`, `fixed`, `enum`          | [String](../sql-reference/data-types/string.md)                                                                       | `bytes`                      |
| `bytes`, `string`, `fixed`                  | [FixedString(N)](../sql-reference/data-types/fixedstring.md)                                                          | `fixed(N)`                   |
| `enum`                                      | [Enum(8\|16)](../sql-reference/data-types/enum.md)                                                                    | `enum`                       |
| `array(T)`                                  | [Array(T)](../sql-reference/data-types/array.md)                                                                      | `array(T)`                   |
| `union(null, T)`, `union(T, null)`          | [Nullable(T)](../sql-reference/data-types/date.md)                                                                    | `union(null, T)`             |
| `null`                                      | [Nullable(Nothing)](../sql-reference/data-types/special-data-types/nothing.md)                                        | `null`                       |
| `int (date)` \*                             | [Date](../sql-reference/data-types/date.md)                                                                           | `int (date)` \*              |
| `long (timestamp-millis)` \*                | [DateTime64(3)](../sql-reference/data-types/datetime.md)                                                              | `long (timestamp-millis)` \* |
| `long (timestamp-micros)` \*                | [DateTime64(6)](../sql-reference/data-types/datetime.md)                                                              | `long (timestamp-micros)` \* |
A
Andrew Onyshchuk 已提交
1142

H
hcz 已提交
1143
\* [Avro logical types](https://avro.apache.org/docs/current/spec.html#Logical+Types)
A
Andrew Onyshchuk 已提交
1144 1145 1146

Unsupported Avro data types: `record` (non-root), `map`

1147
Unsupported Avro logical data types: `time-millis`, `time-micros`, `duration`
A
Andrew Onyshchuk 已提交
1148

1149
### Inserting Data {#inserting-data-1}
A
Andrew Onyshchuk 已提交
1150 1151 1152

To insert data from an Avro file into ClickHouse table:

1153
``` bash
A
Andrew Onyshchuk 已提交
1154 1155 1156 1157 1158
$ cat file.avro | clickhouse-client --query="INSERT INTO {some_table} FORMAT Avro"
```

The root schema of input Avro file must be of `record` type.

1159
To find the correspondence between table columns and fields of Avro schema ClickHouse compares their names. This comparison is case-sensitive.
A
Andrew Onyshchuk 已提交
1160 1161
Unused fields are skipped.

1162
Data types of ClickHouse table columns can differ from the corresponding fields of the Avro data inserted. When inserting data, ClickHouse interprets data types according to the table above and then [casts](../sql-reference/functions/type-conversion-functions.md#type_conversion_function-cast) the data to corresponding column type.
A
Andrew Onyshchuk 已提交
1163

1164
### Selecting Data {#selecting-data-1}
A
Andrew Onyshchuk 已提交
1165 1166 1167

To select data from ClickHouse table into an Avro file:

1168
``` bash
A
Andrew Onyshchuk 已提交
1169 1170 1171 1172 1173
$ clickhouse-client --query="SELECT * FROM {some_table} FORMAT Avro" > file.avro
```

Column names must:

1174 1175
-   start with `[A-Za-z_]`
-   subsequently contain only `[A-Za-z0-9_]`
A
Andrew Onyshchuk 已提交
1176

A
Alexey Milovidov 已提交
1177
Output Avro file compression and sync interval can be configured with [output_format_avro_codec](../operations/settings/settings.md#settings-output_format_avro_codec) and [output_format_avro_sync_interval](../operations/settings/settings.md#settings-output_format_avro_sync_interval) respectively.
A
Andrew Onyshchuk 已提交
1178

I
Ivan Blinkov 已提交
1179
## AvroConfluent {#data-format-avro-confluent}
A
Andrew Onyshchuk 已提交
1180 1181 1182 1183 1184 1185 1186

AvroConfluent supports decoding single-object Avro messages commonly used with [Kafka](https://kafka.apache.org/) and [Confluent Schema Registry](https://docs.confluent.io/current/schema-registry/index.html).

Each Avro message embeds a schema id that can be resolved to the actual schema with help of the Schema Registry.

Schemas are cached once resolved.

A
Alexey Milovidov 已提交
1187
Schema Registry URL is configured with [format_avro_schema_registry_url](../operations/settings/settings.md#format_avro_schema_registry_url).
A
Andrew Onyshchuk 已提交
1188

1189
### Data Types Matching {#data_types-matching-1}
A
Andrew Onyshchuk 已提交
1190

1191
Same as [Avro](#data-format-avro).
A
Andrew Onyshchuk 已提交
1192

1193
### Usage {#usage}
A
Andrew Onyshchuk 已提交
1194

I
Ivan Blinkov 已提交
1195
To quickly verify schema resolution you can use [kafkacat](https://github.com/edenhill/kafkacat) with [clickhouse-local](../operations/utilities/clickhouse-local.md):
A
Andrew Onyshchuk 已提交
1196

1197
``` bash
A
Andrew Onyshchuk 已提交
1198 1199 1200 1201 1202 1203
$ kafkacat -b kafka-broker  -C -t topic1 -o beginning -f '%s' -c 3 | clickhouse-local   --input-format AvroConfluent --format_avro_schema_registry_url 'http://schema-registry' -S "field1 Int64, field2 String"  -q 'select *  from table'
1 a
2 b
3 c
```

1204
To use `AvroConfluent` with [Kafka](../engines/table-engines/integrations/kafka.md):
1205 1206

``` sql
A
Andrew Onyshchuk 已提交
1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224
CREATE TABLE topic1_stream
(
    field1 String,
    field2 String
)
ENGINE = Kafka()
SETTINGS
kafka_broker_list = 'kafka-broker',
kafka_topic_list = 'topic1',
kafka_group_name = 'group1',
kafka_format = 'AvroConfluent';

SET format_avro_schema_registry_url = 'http://schema-registry';

SELECT * FROM topic1_stream;
```

!!! note "Warning"
1225
    Setting `format_avro_schema_registry_url` needs to be configured in `users.xml` to maintain it’s value after a restart. Also you can use the `format_avro_schema_registry_url` setting of the `Kafka` table engine.
A
Andrew Onyshchuk 已提交
1226

I
Ivan Blinkov 已提交
1227
## Parquet {#data-format-parquet}
1228

H
hcz 已提交
1229
[Apache Parquet](https://parquet.apache.org/) is a columnar storage format widespread in the Hadoop ecosystem. ClickHouse supports read and write operations for this format.
1230

1231
### Data Types Matching {#data_types-matching-2}
1232

1233
The table below shows supported data types and how they match ClickHouse [data types](../sql-reference/data-types/index.md) in `INSERT` and `SELECT` queries.
1234

1235 1236
| Parquet data type (`INSERT`) | ClickHouse data type                                      | Parquet data type (`SELECT`) |
|------------------------------|-----------------------------------------------------------|------------------------------|
1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251
| `UINT8`, `BOOL`              | [UInt8](../sql-reference/data-types/int-uint.md)          | `UINT8`                      |
| `INT8`                       | [Int8](../sql-reference/data-types/int-uint.md)           | `INT8`                       |
| `UINT16`                     | [UInt16](../sql-reference/data-types/int-uint.md)         | `UINT16`                     |
| `INT16`                      | [Int16](../sql-reference/data-types/int-uint.md)          | `INT16`                      |
| `UINT32`                     | [UInt32](../sql-reference/data-types/int-uint.md)         | `UINT32`                     |
| `INT32`                      | [Int32](../sql-reference/data-types/int-uint.md)          | `INT32`                      |
| `UINT64`                     | [UInt64](../sql-reference/data-types/int-uint.md)         | `UINT64`                     |
| `INT64`                      | [Int64](../sql-reference/data-types/int-uint.md)          | `INT64`                      |
| `FLOAT`, `HALF_FLOAT`        | [Float32](../sql-reference/data-types/float.md)           | `FLOAT`                      |
| `DOUBLE`                     | [Float64](../sql-reference/data-types/float.md)           | `DOUBLE`                     |
| `DATE32`                     | [Date](../sql-reference/data-types/date.md)               | `UINT16`                     |
| `DATE64`, `TIMESTAMP`        | [DateTime](../sql-reference/data-types/datetime.md)       | `UINT32`                     |
| `STRING`, `BINARY`           | [String](../sql-reference/data-types/string.md)           | `STRING`                     |
| —                            | [FixedString](../sql-reference/data-types/fixedstring.md) | `STRING`                     |
| `DECIMAL`                    | [Decimal](../sql-reference/data-types/decimal.md)         | `DECIMAL`                    |
1252

1253
ClickHouse supports configurable precision of `Decimal` type. The `INSERT` query treats the Parquet `DECIMAL` type as the ClickHouse `Decimal128` type.
1254

1255 1256
Unsupported Parquet data types: `DATE32`, `TIME32`, `FIXED_SIZE_BINARY`, `JSON`, `UUID`, `ENUM`.

A
Alexey Milovidov 已提交
1257
Data types of ClickHouse table columns can differ from the corresponding fields of the Parquet data inserted. When inserting data, ClickHouse interprets data types according to the table above and then [cast](../sql-reference/functions/type-conversion-functions/#type_conversion_function-cast) the data to that data type which is set for the ClickHouse table column.
1258

1259
### Inserting and Selecting Data {#inserting-and-selecting-data}
1260

A
alexey-milovidov 已提交
1261
You can insert Parquet data from a file into ClickHouse table by the following command:
1262

1263
``` bash
1264
$ cat {filename} | clickhouse-client --query="INSERT INTO {some_table} FORMAT Parquet"
1265 1266 1267 1268
```

You can select data from a ClickHouse table and save them into some file in the Parquet format by the following command:

1269
``` bash
1270 1271 1272
$ clickhouse-client --query="SELECT * FROM {some_table} FORMAT Parquet" > {some_file.pq}
```

1273
To exchange data with Hadoop, you can use [HDFS table engine](../engines/table-engines/integrations/hdfs.md).
1274

A
Alexander Kuzmenkov 已提交
1275
## Arrow {#data-format-arrow}
H
hcz 已提交
1276 1277 1278

[Apache Arrow](https://arrow.apache.org/) comes with two built-in columnar storage formats. ClickHouse supports read and write operations for these formats.

1279
`Arrow` is Apache Arrow’s “file mode” format. It is designed for in-memory random access.
H
hcz 已提交
1280

A
Alexander Kuzmenkov 已提交
1281
## ArrowStream {#data-format-arrow-stream}
H
hcz 已提交
1282

1283
`ArrowStream` is Apache Arrow’s “stream mode” format. It is designed for in-memory stream processing.
H
hcz 已提交
1284

I
Ivan Blinkov 已提交
1285
## ORC {#data-format-orc}
1286

1287
[Apache ORC](https://orc.apache.org/) is a columnar storage format widespread in the Hadoop ecosystem. You can only insert data in this format to ClickHouse.
1288

1289
### Data Types Matching {#data_types-matching-3}
1290

1291
The table below shows supported data types and how they match ClickHouse [data types](../sql-reference/data-types/index.md) in `INSERT` queries.
1292

1293 1294
| ORC data type (`INSERT`) | ClickHouse data type                                |
|--------------------------|-----------------------------------------------------|
1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308
| `UINT8`, `BOOL`          | [UInt8](../sql-reference/data-types/int-uint.md)    |
| `INT8`                   | [Int8](../sql-reference/data-types/int-uint.md)     |
| `UINT16`                 | [UInt16](../sql-reference/data-types/int-uint.md)   |
| `INT16`                  | [Int16](../sql-reference/data-types/int-uint.md)    |
| `UINT32`                 | [UInt32](../sql-reference/data-types/int-uint.md)   |
| `INT32`                  | [Int32](../sql-reference/data-types/int-uint.md)    |
| `UINT64`                 | [UInt64](../sql-reference/data-types/int-uint.md)   |
| `INT64`                  | [Int64](../sql-reference/data-types/int-uint.md)    |
| `FLOAT`, `HALF_FLOAT`    | [Float32](../sql-reference/data-types/float.md)     |
| `DOUBLE`                 | [Float64](../sql-reference/data-types/float.md)     |
| `DATE32`                 | [Date](../sql-reference/data-types/date.md)         |
| `DATE64`, `TIMESTAMP`    | [DateTime](../sql-reference/data-types/datetime.md) |
| `STRING`, `BINARY`       | [String](../sql-reference/data-types/string.md)     |
| `DECIMAL`                | [Decimal](../sql-reference/data-types/decimal.md)   |
1309

1310
ClickHouse supports configurable precision of the `Decimal` type. The `INSERT` query treats the ORC `DECIMAL` type as the ClickHouse `Decimal128` type.
1311 1312 1313

Unsupported ORC data types: `DATE32`, `TIME32`, `FIXED_SIZE_BINARY`, `JSON`, `UUID`, `ENUM`.

1314
The data types of ClickHouse table columns don’t have to match the corresponding ORC data fields. When inserting data, ClickHouse interprets data types according to the table above and then [casts](../sql-reference/functions/type-conversion-functions.md#type_conversion_function-cast) the data to the data type set for the ClickHouse table column.
1315

1316
### Inserting Data {#inserting-data-2}
1317

1318
You can insert ORC data from a file into ClickHouse table by the following command:
1319

1320
``` bash
1321
$ cat filename.orc | clickhouse-client --query="INSERT INTO some_table FORMAT ORC"
1322
```
1323

1324
To exchange data with Hadoop, you can use [HDFS table engine](../engines/table-engines/integrations/hdfs.md).
A
alexey-milovidov 已提交
1325

1326 1327
## LineAsString {#lineasstring}

1328
In this format, every line of input data is interpreted as a single string value. This format can only be parsed for table with a single field of type [String](../sql-reference/data-types/string.md). The remaining columns must be set to [DEFAULT](../sql-reference/statements/create/table.md#default) or [MATERIALIZED](../sql-reference/statements/create/table.md#materialized), or omitted.
1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350

**Example**

Query:

``` sql
DROP TABLE IF EXISTS line_as_string;
CREATE TABLE line_as_string (field String) ENGINE = Memory;
INSERT INTO line_as_string FORMAT LineAsString "I love apple", "I love banana", "I love orange";
SELECT * FROM line_as_string;
```

Result:

``` text
┌─field─────────────────────────────────────────────┐
│ "I love apple", "I love banana", "I love orange"; │
└───────────────────────────────────────────────────┘
```

## Regexp {#data-format-regexp}

1351 1352
Each line of imported data is parsed according to the regular expression.

1353 1354 1355 1356 1357 1358 1359 1360 1361
When working with the `Regexp` format, you can use the following settings:

- `format_regexp` — [String](../sql-reference/data-types/string.md). Contains regular expression in the [re2](https://github.com/google/re2/wiki/Syntax) format.
- `format_regexp_escaping_rule` — [String](../sql-reference/data-types/string.md). The following escaping rules are supported:
    - CSV (similarly to [CSV](#csv))
    - JSON (similarly to [JSONEachRow](#jsoneachrow))
    - Escaped (similarly to [TSV](#tabseparated))
    - Quoted (similarly to [Values](#data-format-values))
    - Raw (extracts subpatterns as a whole, no escaping rules)
A
Alexey Milovidov 已提交
1362
- `format_regexp_skip_unmatched` — [UInt8](../sql-reference/data-types/int-uint.md). Defines the need to throw an exeption in case the `format_regexp` expression does not match the imported data. Can be set to `0` or `1`.
1363

A
Alexey Milovidov 已提交
1364
**Usage**
1365

A
Alexey Milovidov 已提交
1366
The regular expression from `format_regexp` setting is applied to every line of imported data. The number of subpatterns in the regular expression must be equal to the number of columns in imported dataset.
1367

A
Alexey Milovidov 已提交
1368
Lines of the imported data must be separated by newline character `'\n'` or DOS-style newline `"\r\n"`.
1369

A
Alexey Milovidov 已提交
1370
The content of every matched subpattern is parsed with the method of corresponding data type, according to `format_regexp_escaping_rule` setting.
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

If the regular expression does not match the line and `format_regexp_skip_unmatched` is set to 1, the line is silently skipped. If `format_regexp_skip_unmatched` is set to 0, exception is thrown.

**Example**

Consider the file data.tsv:

```text
id: 1 array: [1,2,3] string: str1 date: 2020-01-01
id: 2 array: [1,2,3] string: str2 date: 2020-01-02
id: 3 array: [1,2,3] string: str3 date: 2020-01-03
```
and the table:

```sql
CREATE TABLE imp_regex_table (id UInt32, array Array(UInt32), string String, date Date) ENGINE = Memory;
```

Import command:

```bash
$ cat data.tsv | clickhouse-client  --query "INSERT INTO imp_regex_table FORMAT Regexp SETTINGS format_regexp='id: (.+?) array: (.+?) string: (.+?) date: (.+?)', format_regexp_escaping_rule='Escaped', format_regexp_skip_unmatched=0;"
```

Query:

```sql
SELECT * FROM imp_regex_table;
```

Result:

O
Olga Revyakina 已提交
1403
```text
1404 1405 1406 1407 1408 1409 1410
┌─id─┬─array───┬─string─┬───────date─┐
│  1 │ [1,2,3] │ str1   │ 2020-01-01 │
│  2 │ [1,2,3] │ str2   │ 2020-01-02 │
│  3 │ [1,2,3] │ str3   │ 2020-01-03 │
└────┴─────────┴────────┴────────────┘
```

I
Ivan Blinkov 已提交
1411
## Format Schema {#formatschema}
1412 1413

The file name containing the format schema is set by the setting `format_schema`.
1414
It’s required to set this setting when it is used one of the formats `Cap'n Proto` and `Protobuf`.
1415
The format schema is a combination of a file name and the name of a message type in this file, delimited by a colon,
1416
e.g. `schemafile.proto:MessageType`.
1417
If the file has the standard extension for the format (for example, `.proto` for `Protobuf`),
1418
it can be omitted and in this case, the format schema looks like `schemafile:MessageType`.
1419

1420
If you input or output data via the [client](../interfaces/cli.md) in the [interactive mode](../interfaces/cli.md#cli_usage), the file name specified in the format schema
1421
can contain an absolute path or a path relative to the current directory on the client.
1422 1423 1424
If you use the client in the [batch mode](../interfaces/cli.md#cli_usage), the path to the schema must be relative due to security reasons.

If you input or output data via the [HTTP interface](../interfaces/http.md) the file name specified in the format schema
A
Alexey Milovidov 已提交
1425
should be located in the directory specified in [format_schema_path](../operations/server-configuration-parameters/settings.md#server_configuration_parameters-format_schema_path)
1426 1427
in the server configuration.

I
Ivan Blinkov 已提交
1428
## Skipping Errors {#skippingerrors}
A
Alexander Tokmakov 已提交
1429

A
Alexey Milovidov 已提交
1430 1431
Some formats such as `CSV`, `TabSeparated`, `TSKV`, `JSONEachRow`, `Template`, `CustomSeparated` and `Protobuf` can skip broken row if parsing error occurred and continue parsing from the beginning of next row. See [input_format_allow_errors_num](../operations/settings/settings.md#settings-input_format_allow_errors_num) and
[input_format_allow_errors_ratio](../operations/settings/settings.md#settings-input_format_allow_errors_ratio) settings.
A
Alexander Tokmakov 已提交
1432
Limitations:
1433 1434
- In case of parsing error `JSONEachRow` skips all data until the new line (or EOF), so rows must be delimited by `\n` to count errors correctly.
- `Template` and `CustomSeparated` use delimiter after the last column and delimiter between rows to find the beginning of next row, so skipping errors works only if at least one of them is not empty.
1435

A
annvsh 已提交
1436 1437
## RawBLOB {#rawblob}

A
Fixed  
annvsh 已提交
1438
In this format, all input data is read to a single value. It is possible to parse only a table with a single field of type [String](../sql-reference/data-types/string.md) or similar.
A
Fixed  
annvsh 已提交
1439 1440
The result is output in binary format without delimiters and escaping. If more than one value is output, the format is ambiguous, and it will be impossible to read the data back.

A
Fixed  
annvsh 已提交
1441
Below is a comparison of the formats `RawBLOB` and [TabSeparatedRaw](#tabseparatedraw).
A
Fixed  
annvsh 已提交
1442 1443 1444 1445
`RawBLOB`:
- data is output in binary format, no escaping;
- there are no delimiters between values;
- no newline at the end of each value.
A
Fixed  
annvsh 已提交
1446
[TabSeparatedRaw] (#tabseparatedraw):
A
alexey-milovidov 已提交
1447 1448 1449
- data is output without escaping;
- the rows contain values separated by tabs;
- there is a line feed after the last value in every row.
A
Fixed  
annvsh 已提交
1450

A
Fixed  
annvsh 已提交
1451 1452
The following is a comparison of the `RawBLOB` and [RowBinary](#rowbinary) formats.
`RawBLOB`:
A
alexey-milovidov 已提交
1453 1454 1455
- String fields are output without being prefixed by length.
`RowBinary`:
- String fields are represented as length in varint format (unsigned [LEB128] (https://en.wikipedia.org/wiki/LEB128)), followed by the bytes of the string.
A
Fixed  
annvsh 已提交
1456

A
alexey-milovidov 已提交
1457
When an empty data is passed to the `RawBLOB` input, ClickHouse throws an exception:
A
Fixed  
annvsh 已提交
1458

A
Fixed  
annvsh 已提交
1459
``` text
A
annvsh 已提交
1460 1461 1462 1463 1464 1465
Code: 108. DB::Exception: No data to insert
```

**Example**

``` bash
A
Fixed  
annvsh 已提交
1466
$ clickhouse-client --query "CREATE TABLE {some_table} (a String) ENGINE = Memory;"
A
Fixed  
annvsh 已提交
1467 1468
$ cat {filename} | clickhouse-client --query="INSERT INTO {some_table} FORMAT RawBLOB"
$ clickhouse-client --query "SELECT * FROM {some_table} FORMAT RawBLOB" | md5sum
A
annvsh 已提交
1469 1470 1471 1472 1473 1474 1475 1476
```

Result:

``` text
f9725a22f9191e064120d718e26862a9  -
```

1477
[Original article](https://clickhouse.tech/docs/en/interfaces/formats/) <!--hide-->