Formats for Input and Output Data
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 a dictionary. A format supported for output can be used to arrange the
results of a SELECT
, and to perform INSERT
s into a file-backed table.
All format names are case insensitive.
The supported formats are:
You can control some format processing parameters with the ClickHouse settings. For more information read the Settings section.
TabSeparated
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.
This format is also available under the name TSV
.
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.
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:
SELECT EventDate, count() AS c FROM test.hits GROUP BY EventDate WITH TOTALS ORDER BY EventDate FORMAT TabSeparated
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
1970-01-01 8873898
2014-03-17 1031592
2014-03-23 1406958
Data Formatting
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.
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. 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.
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.
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.
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:
Hello\nworld
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.
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.
NULL is formatted according to setting format_tsv_null_representation (default value is \N
).
In input data, ENUM values can be represented as names or as ids. First, we try to match the input value to the ENUM name. If we fail and the input value is a number, we try to match this number to ENUM id. If input data contains only ENUM ids, it's recommended to enable the setting input_format_tsv_enum_as_number to optimize ENUM parsing.
Each element of Nested structures is represented as an array.
For example:
CREATE TABLE nestedt
(
`id` UInt8,
`aux` Nested(
a UInt8,
b String
)
)
ENGINE = TinyLog
INSERT INTO nestedt Values ( 1, [1], ['a'])
SELECT * FROM nestedt FORMAT TSV
1 [1] ['a']
TabSeparated format settings
- format_tsv_null_representation - custom NULL representation in TSV format. Default value -
\N
. - input_format_tsv_empty_as_default - treat empty fields in TSV input as default values. Default value -
false
. For complex default expressions input_format_defaults_for_omitted_fields must be enabled too. - input_format_tsv_enum_as_number - treat inserted enum values in TSV formats as enum indices. Default value -
false
. - input_format_tsv_use_best_effort_in_schema_inference - use some tweaks and heuristics to infer schema in TSV format. If disabled, all fields will be inferred as Strings. Default value -
true
. - output_format_tsv_crlf_end_of_line - if it is set true, end of line in TSV output format will be
\r\n
instead of\n
. Default value -false
. - input_format_tsv_crlf_end_of_line - if it is set true, end of line in TSV input format will be
\r\n
instead of\n
. Default value -false
. - input_format_tsv_skip_first_lines - skip specified number of lines at the beginning of data. Default value -
0
. - input_format_tsv_detect_header - automatically detect header with names and types in TSV format. Default value -
true
. - input_format_tsv_skip_trailing_empty_lines - skip trailing empty lines at the end of data. Default value -
false
. - input_format_tsv_allow_variable_number_of_columns - allow variable number of columns in TSV format, ignore extra columns and use default values on missing columns. Default value -
false
.
TabSeparatedRaw
Differs from TabSeparated
format in that the rows are written without escaping.
When parsing with this format, tabs or linefeeds are not allowed in each field.
This format is also available under the names TSVRaw
, Raw
.
TabSeparatedWithNames
Differs from the TabSeparated
format in that the column names are written in the first row.
During parsing, the first row is expected to contain the column names. You can use column names to determine their position and to check their correctness.
If setting input_format_with_names_use_header is set to 1, the columns from the input data will be mapped to the columns of the table by their names, columns with unknown names will be skipped if setting input_format_skip_unknown_fields is set to 1. Otherwise, the first row will be skipped.
This format is also available under the name TSVWithNames
.
TabSeparatedWithNamesAndTypes
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.
If setting input_format_with_names_use_header is set to 1, the columns from the input data will be mapped to the columns in the table by their names, columns with unknown names will be skipped if setting input_format_skip_unknown_fields is set to 1. Otherwise, the first row will be skipped. If setting input_format_with_types_use_header is set to 1, the types from input data will be compared with the types of the corresponding columns from the table. Otherwise, the second row will be skipped.
This format is also available under the name TSVWithNamesAndTypes
.
TabSeparatedRawWithNames
Differs from TabSeparatedWithNames
format in that the rows are written without escaping.
When parsing with this format, tabs or linefeeds are not allowed in each field.
This format is also available under the names TSVRawWithNames
, RawWithNames
.
TabSeparatedRawWithNamesAndTypes
Differs from TabSeparatedWithNamesAndTypes
format in that the rows are written without escaping.
When parsing with this format, tabs or linefeeds are not allowed in each field.
This format is also available under the names TSVRawWithNamesAndNames
, RawWithNamesAndNames
.
Template
This format allows specifying a custom format string with placeholders for values with a specified escaping rule.
It uses settings format_template_resultset
, format_template_row
(format_template_row_format
), 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)
Setting format_template_row
specifies the path to the file containing format strings for rows with the following syntax:
delimiter_1${column_1:serializeAs_1}delimiter_2${column_2:serializeAs_2} ... delimiter_N
,
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:
CSV
,JSON
,XML
(similar to the formats of the same names)Escaped
(similar toTSV
)Quoted
(similar toValues
)Raw
(without escaping, similar toTSVRaw
)None
(no escaping rule, see further)
If an escaping rule is omitted, then None
will be used. XML
is suitable only for output.
So, for the following format string:
Search phrase: ${SearchPhrase:Quoted}, count: ${c:Escaped}, ad price: $$${price:JSON};
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:
Search phrase: 'bathroom interior design', count: 2166, ad price: $3;
In cases where it is challenging or not possible to deploy format output configuration for the template format to a directory on all nodes in a cluster, or if the format is trivial then format_template_row_format
can be used to set the template string directly in the query, rather than a path to the file which contains it.
The format_template_rows_between_delimiter
setting specifies the delimiter between rows, which is printed (or expected) after every row except the last one (\n
by default)
Setting format_template_resultset
specifies the path to the file, which contains a format string for resultset. Setting format_template_resultset_format
can be used to set the template string for the result set directly in the query itself. 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:
data
is the rows with data informat_template_row
format, separated byformat_template_rows_between_delimiter
. This placeholder must be the first placeholder in the format string.totals
is the row with total values informat_template_row
format (when using WITH TOTALS)min
is the row with minimum values informat_template_row
format (when extremes are set to 1)max
is the row with maximum values informat_template_row
format (when extremes are set to 1)rows
is the total number of output rowsrows_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.time
is the request execution time in secondsrows_read
is the number of rows has been readbytes_read
is the number of bytes (uncompressed) has been read
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 the default value.
For insert queries format allows skipping some columns or fields if prefix or suffix (see example).
Select example:
SELECT SearchPhrase, count() AS c FROM test.hits GROUP BY SearchPhrase ORDER BY c DESC LIMIT 5 FORMAT Template SETTINGS
format_template_resultset = '/some/path/resultset.format', format_template_row = '/some/path/row.format', format_template_rows_between_delimiter = '\n '
/some/path/resultset.format
:
<!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>
${data}
</table>
<table border="1"> <caption>Max</caption>
${max}
</table>
<b>Processed ${rows_read:XML} rows in ${time:XML} sec</b>
</body>
</html>
/some/path/row.format
:
<tr> <td>${0:XML}</td> <td>${1:XML}</td> </tr>
Result:
<!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>clickhouse</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>
Insert example:
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
INSERT INTO UserActivity SETTINGS
format_template_resultset = '/some/path/resultset.format', format_template_row = '/some/path/row.format'
FORMAT Template
/some/path/resultset.format
:
Some header\n${data}\nTotal rows: ${:CSV}\n
/some/path/row.format
:
Page views: ${PageViews:CSV}, User id: ${UserID:CSV}, Useless field: ${:CSV}, Duration: ${Duration:CSV}, Sign: ${Sign:CSV}
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.
All delimiters in the input data must be strictly equal to delimiters in specified format strings.
TemplateIgnoreSpaces
This format is suitable only for input.
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 specifying 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 the values of columns have the same order in all rows. For example, the following request can be used for inserting data from its output example of format JSON:
INSERT INTO table_name SETTINGS
format_template_resultset = '/some/path/resultset.format', format_template_row = '/some/path/row.format', format_template_rows_between_delimiter = ','
FORMAT TemplateIgnoreSpaces
/some/path/resultset.format
:
{${}"meta"${}:${:JSON},${}"data"${}:${}[${data}]${},${}"totals"${}:${:JSON},${}"extremes"${}:${:JSON},${}"rows"${}:${:JSON},${}"rows_before_limit_at_least"${}:${:JSON}${}}
/some/path/row.format
:
{${}"SearchPhrase"${}:${}${phrase:JSON}${},${}"c"${}:${}${cnt:JSON}${}}
TSKV
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.
SearchPhrase= count()=8267016
SearchPhrase=bathroom interior design count()=2166
SearchPhrase=clickhouse 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
NULL is formatted as \N
.
SELECT * FROM t_null FORMAT TSKV
x=1 y=\N
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.
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.
During import, columns with unknown names will be skipped if setting input_format_skip_unknown_fields is set to 1.
CSV
Comma Separated Values format (RFC).
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. 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).
$ clickhouse-client --format_csv_delimiter="|" --query="INSERT INTO test.csv FORMAT CSV" < data.csv
*By default, the delimiter is ,
. See the format_csv_delimiter setting for more information.
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.
NULL
is formatted according to setting format_csv_null_representation (default value is \N
).
In input data, ENUM values can be represented as names or as ids. First, we try to match the input value to the ENUM name. If we fail and the input value is a number, we try to match this number to the ENUM id. If input data contains only ENUM ids, it's recommended to enable the setting input_format_csv_enum_as_number to optimize ENUM parsing.
The CSV format supports the output of totals and extremes the same way as TabSeparated
.
CSV format settings
- format_csv_delimiter - the character to be considered as a delimiter in CSV data. Default value -
,
. - format_csv_allow_single_quotes - allow strings in single quotes. Default value -
true
. - format_csv_allow_double_quotes - allow strings in double quotes. Default value -
true
. - format_csv_null_representation - custom NULL representation in CSV format. Default value -
\N
. - input_format_csv_empty_as_default - treat empty fields in CSV input as default values. Default value -
true
. For complex default expressions, input_format_defaults_for_omitted_fields must be enabled too. - input_format_csv_enum_as_number - treat inserted enum values in CSV formats as enum indices. Default value -
false
. - input_format_csv_use_best_effort_in_schema_inference - use some tweaks and heuristics to infer schema in CSV format. If disabled, all fields will be inferred as Strings. Default value -
true
. - input_format_csv_arrays_as_nested_csv - when reading Array from CSV, expect that its elements were serialized in nested CSV and then put into string. Default value -
false
. - output_format_csv_crlf_end_of_line - if it is set to true, end of line in CSV output format will be
\r\n
instead of\n
. Default value -false
. - input_format_csv_skip_first_lines - skip the specified number of lines at the beginning of data. Default value -
0
. - input_format_csv_detect_header - automatically detect header with names and types in CSV format. Default value -
true
. - input_format_csv_skip_trailing_empty_lines - skip trailing empty lines at the end of data. Default value -
false
. - input_format_csv_trim_whitespaces - trim spaces and tabs in non-quoted CSV strings. Default value -
true
. - input_format_csv_allow_whitespace_or_tab_as_delimiter - Allow to use whitespace or tab as field delimiter in CSV strings. Default value -
false
. - input_format_csv_allow_variable_number_of_columns - allow variable number of columns in CSV format, ignore extra columns and use default values on missing columns. Default value -
false
. - input_format_csv_use_default_on_bad_values - Allow to set default value to column when CSV field deserialization failed on bad value. Default value -
false
. - input_format_csv_try_infer_numbers_from_strings - Try to infer numbers from string fields while schema inference. Default value -
false
.
CSVWithNames
Also prints the header row with column names, similar to TabSeparatedWithNames.
If setting input_format_with_names_use_header is set to 1, the columns from input data will be mapped to the columns from the table by their names, columns with unknown names will be skipped if setting input_format_skip_unknown_fields is set to 1. Otherwise, the first row will be skipped.
CSVWithNamesAndTypes
Also prints two header rows with column names and types, similar to TabSeparatedWithNamesAndTypes.
If setting input_format_with_names_use_header is set to 1, the columns from input data will be mapped to the columns from the table by their names, columns with unknown names will be skipped if setting input_format_skip_unknown_fields is set to 1. Otherwise, the first row will be skipped. If setting input_format_with_types_use_header is set to 1, the types from input data will be compared with the types of the corresponding columns from the table. Otherwise, the second row will be skipped.
CustomSeparated
Similar to Template, but it prints or reads all names and types of columns and uses escaping rule from format_custom_escaping_rule setting and delimiters from 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 settings, not from format strings.
Additional settings:
- input_format_custom_detect_header - enables automatic detection of header with names and types if any. Default value -
true
. - input_format_custom_skip_trailing_empty_lines - skip trailing empty lines at the end of file . Default value -
false
. - input_format_custom_allow_variable_number_of_columns - allow variable number of columns in CustomSeparated format, ignore extra columns and use default values on missing columns. Default value -
false
.
There is also CustomSeparatedIgnoreSpaces
format, which is similar to TemplateIgnoreSpaces.
CustomSeparatedWithNames
Also prints the header row with column names, similar to TabSeparatedWithNames.
If setting input_format_with_names_use_header is set to 1, the columns from input data will be mapped to the columns from the table by their names, columns with unknown names will be skipped if setting input_format_skip_unknown_fields is set to 1. Otherwise, the first row will be skipped.
CustomSeparatedWithNamesAndTypes
Also prints two header rows with column names and types, similar to TabSeparatedWithNamesAndTypes.
If setting input_format_with_names_use_header is set to 1, the columns from input data will be mapped to the columns from the table by their names, columns with unknown names will be skipped if setting input_format_skip_unknown_fields is set to 1. Otherwise, the first row will be skipped. If setting input_format_with_types_use_header is set to 1, the types from input data will be compared with the types of the corresponding columns from the table. Otherwise, the second row will be skipped.
SQLInsert
Outputs data as a sequence of INSERT INTO table (columns...) VALUES (...), (...) ...;
statements.
Example:
SELECT number AS x, number + 1 AS y, 'Hello' AS z FROM numbers(10) FORMAT SQLInsert SETTINGS output_format_sql_insert_max_batch_size = 2
INSERT INTO table (x, y, z) VALUES (0, 1, 'Hello'), (1, 2, 'Hello');
INSERT INTO table (x, y, z) VALUES (2, 3, 'Hello'), (3, 4, 'Hello');
INSERT INTO table (x, y, z) VALUES (4, 5, 'Hello'), (5, 6, 'Hello');
INSERT INTO table (x, y, z) VALUES (6, 7, 'Hello'), (7, 8, 'Hello');
INSERT INTO table (x, y, z) VALUES (8, 9, 'Hello'), (9, 10, 'Hello');
To read data output by this format you can use MySQLDump input format.
SQLInsert format settings
- output_format_sql_insert_max_batch_size - The maximum number of rows in one INSERT statement. Default value -
65505
. - output_format_sql_insert_table_name - The name of the table in the output INSERT query. Default value -
'table'
. - output_format_sql_insert_include_column_names - Include column names in INSERT query. Default value -
true
. - output_format_sql_insert_use_replace - Use REPLACE statement instead of INSERT. Default value -
false
. - output_format_sql_insert_quote_names - Quote column names with "`" characters. Default value -
true
.
JSON
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:
SELECT SearchPhrase, count() AS c FROM test.hits GROUP BY SearchPhrase WITH TOTALS ORDER BY c DESC LIMIT 5 FORMAT JSON
{
"meta":
[
{
"name": "num",
"type": "Int32"
},
{
"name": "str",
"type": "String"
},
{
"name": "arr",
"type": "Array(UInt8)"
}
],
"data":
[
{
"num": 42,
"str": "hello",
"arr": [0,1]
},
{
"num": 43,
"str": "hello",
"arr": [0,1,2]
},
{
"num": 44,
"str": "hello",
"arr": [0,1,2,3]
}
],
"rows": 3,
"rows_before_limit_at_least": 3,
"statistics":
{
"elapsed": 0.001137687,
"rows_read": 3,
"bytes_read": 24
}
}
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 to 0.
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.
If the query contains GROUP BY, rows_before_limit_at_least is the exact number of rows there would have been without a LIMIT.
totals
– Total values (when using WITH TOTALS).
extremes
– Extreme values (when extremes are set to 1).
ClickHouse supports NULL, 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 to 1.
See Also
- JSONEachRow format
- output_format_json_array_of_rows setting
For JSON input format, if setting input_format_json_validate_types_from_metadata is set to 1, the types from metadata in input data will be compared with the types of the corresponding columns from the table.
JSONStrings
Differs from JSON only in that data fields are output in strings, not in typed JSON values.
Example:
{
"meta":
[
{
"name": "num",
"type": "Int32"
},
{
"name": "str",
"type": "String"
},
{
"name": "arr",
"type": "Array(UInt8)"
}
],
"data":
[
{
"num": "42",
"str": "hello",
"arr": "[0,1]"
},
{
"num": "43",
"str": "hello",
"arr": "[0,1,2]"
},
{
"num": "44",
"str": "hello",
"arr": "[0,1,2,3]"
}
],
"rows": 3,
"rows_before_limit_at_least": 3,
"statistics":
{
"elapsed": 0.001403233,
"rows_read": 3,
"bytes_read": 24
}
}
JSONColumns
The output of the JSONColumns* formats provides the ClickHouse field name and then the content of each row of the table for that field; visually, the data is rotated 90 degrees to the left.
In this format, all data is represented as a single JSON Object. Note that JSONColumns output format buffers all data in memory to output it as a single block and it can lead to high memory consumption.
Example:
{
"num": [42, 43, 44],
"str": ["hello", "hello", "hello"],
"arr": [[0,1], [0,1,2], [0,1,2,3]]
}
During import, columns with unknown names will be skipped if setting input_format_skip_unknown_fields is set to 1. Columns that are not present in the block will be filled with default values (you can use the input_format_defaults_for_omitted_fields setting here)
JSONColumnsWithMetadata
Differs from JSONColumns format in that it also contains some metadata and statistics (similar to JSON format). Output format buffers all data in memory and then outputs them as a single block, so, it can lead to high memory consumption.
Example:
{
"meta":
[
{
"name": "num",
"type": "Int32"
},
{
"name": "str",
"type": "String"
},
{
"name": "arr",
"type": "Array(UInt8)"
}
],
"data":
{
"num": [42, 43, 44],
"str": ["hello", "hello", "hello"],
"arr": [[0,1], [0,1,2], [0,1,2,3]]
},
"rows": 3,
"rows_before_limit_at_least": 3,
"statistics":
{
"elapsed": 0.000272376,
"rows_read": 3,
"bytes_read": 24
}
}
For JSONColumnsWithMetadata input format, if setting input_format_json_validate_types_from_metadata is set to 1, the types from metadata in input data will be compared with the types of the corresponding columns from the table.
JSONAsString
In this format, a single JSON object is interpreted as a single value. If the input has several JSON objects (comma separated), they are interpreted as separate rows. If the input data is enclosed in square brackets, it is interpreted as an array of JSONs.
This format can only be parsed for a table with a single field of type String. The remaining columns must be set to DEFAULT or MATERIALIZED, or omitted. Once you collect the whole JSON object to string you can use JSON functions to process it.
Examples
Query:
DROP TABLE IF EXISTS json_as_string;
CREATE TABLE json_as_string (json String) ENGINE = Memory;
INSERT INTO json_as_string (json) FORMAT JSONAsString {"foo":{"bar":{"x":"y"},"baz":1}},{},{"any json stucture":1}
SELECT * FROM json_as_string;
Result:
┌─json──────────────────────────────┐
│ {"foo":{"bar":{"x":"y"},"baz":1}} │
│ {} │
│ {"any json stucture":1} │
└───────────────────────────────────┘
An array of JSON objects
Query:
CREATE TABLE json_square_brackets (field String) ENGINE = Memory;
INSERT INTO json_square_brackets FORMAT JSONAsString [{"id": 1, "name": "name1"}, {"id": 2, "name": "name2"}];
SELECT * FROM json_square_brackets;
Result:
┌─field──────────────────────┐
│ {"id": 1, "name": "name1"} │
│ {"id": 2, "name": "name2"} │
└────────────────────────────┘
JSONAsObject
In this format, a single JSON object is interpreted as a single JSON value. If the input has several JSON objects (comma separated), they are interpreted as separate rows. If the input data is enclosed in square brackets, it is interpreted as an array of JSONs.
This format can only be parsed for a table with a single field of type JSON. The remaining columns must be set to DEFAULT or MATERIALIZED.
Examples
Query:
SET allow_experimental_json_type = 1;
CREATE TABLE json_as_object (json JSON) ENGINE = Memory;
INSERT INTO json_as_object (json) FORMAT JSONAsObject {"foo":{"bar":{"x":"y"},"baz":1}},{},{"any json stucture":1}
SELECT * FROM json_as_object FORMAT JSONEachRow;
Result:
{"json":{"foo":{"bar":{"x":"y"},"baz":"1"}}}
{"json":{}}
{"json":{"any json stucture":"1"}}
An array of JSON objects
Query:
SET allow_experimental_json_type = 1;
CREATE TABLE json_square_brackets (field JSON) ENGINE = Memory;
INSERT INTO json_square_brackets FORMAT JSONAsObject [{"id": 1, "name": "name1"}, {"id": 2, "name": "name2"}];
SELECT * FROM json_square_brackets FORMAT JSONEachRow;
Result:
{"field":{"id":"1","name":"name1"}}
{"field":{"id":"2","name":"name2"}}
Columns with default values
SET allow_experimental_json_type = 1;
CREATE TABLE json_as_object (json JSON, time DateTime MATERIALIZED now()) ENGINE = Memory;
INSERT INTO json_as_object (json) FORMAT JSONAsObject {"foo":{"bar":{"x":"y"},"baz":1}};
INSERT INTO json_as_object (json) FORMAT JSONAsObject {};
INSERT INTO json_as_object (json) FORMAT JSONAsObject {"any json stucture":1}
SELECT time, json FROM json_as_object FORMAT JSONEachRow
{"time":"2024-09-16 12:18:10","json":{}}
{"time":"2024-09-16 12:18:13","json":{"any json stucture":"1"}}
{"time":"2024-09-16 12:18:08","json":{"foo":{"bar":{"x":"y"},"baz":"1"}}}
JSONCompact
Differs from JSON only in that data rows are output in arrays, not in objects.
Example:
{
"meta":
[
{
"name": "num",
"type": "Int32"
},
{
"name": "str",
"type": "String"
},
{
"name": "arr",
"type": "Array(UInt8)"
}
],
"data":
[
[42, "hello", [0,1]],
[43, "hello", [0,1,2]],
[44, "hello", [0,1,2,3]]
],
"rows": 3,
"rows_before_limit_at_least": 3,
"statistics":
{
"elapsed": 0.001222069,
"rows_read": 3,
"bytes_read": 24
}
}
JSONCompactStrings
Differs from JSONStrings only in that data rows are output in arrays, not in objects.
Example: f
{
"meta":
[
{
"name": "num",
"type": "Int32"
},
{
"name": "str",
"type": "String"
},
{
"name": "arr",
"type": "Array(UInt8)"
}
],
"data":
[
["42", "hello", "[0,1]"],
["43", "hello", "[0,1,2]"],
["44", "hello", "[0,1,2,3]"]
],
"rows": 3,
"rows_before_limit_at_least": 3,
"statistics":
{
"elapsed": 0.001572097,
"rows_read": 3,
"bytes_read": 24
}
}
JSONCompactColumns
In this format, all data is represented as a single JSON Array. Note that JSONCompactColumns output format buffers all data in memory to output it as a single block and it can lead to high memory consumption
Example:
[
[42, 43, 44],
["hello", "hello", "hello"],
[[0,1], [0,1,2], [0,1,2,3]]
]
Columns that are not present in the block will be filled with default values (you can use input_format_defaults_for_omitted_fields setting here)
JSONEachRow
In this format, ClickHouse outputs each row as a separated, newline-delimited JSON Object.
Example:
{"num":42,"str":"hello","arr":[0,1]}
{"num":43,"str":"hello","arr":[0,1,2]}
{"num":44,"str":"hello","arr":[0,1,2,3]}
While importing data columns with unknown names will be skipped if setting input_format_skip_unknown_fields is set to 1.
PrettyJSONEachRow
Differs from JSONEachRow only in that JSON is pretty formatted with new line delimiters and 4 space indents. Suitable only for output.
Example
{
"num": "42",
"str": "hello",
"arr": [
"0",
"1"
],
"tuple": {
"num": 42,
"str": "world"
}
}
{
"num": "43",
"str": "hello",
"arr": [
"0",
"1",
"2"
],
"tuple": {
"num": 43,
"str": "world"
}
}
JSONStringsEachRow
Differs from JSONEachRow only in that data fields are output in strings, not in typed JSON values.
Example:
{"num":"42","str":"hello","arr":"[0,1]"}
{"num":"43","str":"hello","arr":"[0,1,2]"}
{"num":"44","str":"hello","arr":"[0,1,2,3]"}
JSONCompactEachRow
Differs from JSONEachRow only in that data rows are output in arrays, not in objects.
Example:
[42, "hello", [0,1]]
[43, "hello", [0,1,2]]
[44, "hello", [0,1,2,3]]
JSONCompactStringsEachRow
Differs from JSONCompactEachRow only in that data fields are output in strings, not in typed JSON values.
Example:
["42", "hello", "[0,1]"]
["43", "hello", "[0,1,2]"]
["44", "hello", "[0,1,2,3]"]
JSONEachRowWithProgress
JSONStringsEachRowWithProgress
Differs from JSONEachRow
/JSONStringsEachRow
in that ClickHouse will also yield progress information as JSON values.
{"row":{"num":42,"str":"hello","arr":[0,1]}}
{"row":{"num":43,"str":"hello","arr":[0,1,2]}}
{"row":{"num":44,"str":"hello","arr":[0,1,2,3]}}
{"progress":{"read_rows":"3","read_bytes":"24","written_rows":"0","written_bytes":"0","total_rows_to_read":"3"}}
JSONCompactEachRowWithNames
Differs from JSONCompactEachRow
format in that it also prints the header row with column names, similar to TabSeparatedWithNames.
If setting input_format_with_names_use_header is set to 1, the columns from input data will be mapped to the columns from the table by their names, columns with unknown names will be skipped if setting input_format_skip_unknown_fields is set to 1. Otherwise, the first row will be skipped.
JSONCompactEachRowWithNamesAndTypes
Differs from JSONCompactEachRow
format in that it also prints two header rows with column names and types, similar to TabSeparatedWithNamesAndTypes.
If setting input_format_with_names_use_header is set to 1, the columns from input data will be mapped to the columns from the table by their names, columns with unknown names will be skipped if setting input_format_skip_unknown_fields is set to 1. Otherwise, the first row will be skipped. If setting input_format_with_types_use_header is set to 1, the types from input data will be compared with the types of the corresponding columns from the table. Otherwise, the second row will be skipped.
JSONCompactStringsEachRowWithNames
Differs from JSONCompactStringsEachRow
in that in that it also prints the header row with column names, similar to TabSeparatedWithNames.
If setting input_format_with_names_use_header is set to 1, the columns from input data will be mapped to the columns from the table by their names, columns with unknown names will be skipped if setting input_format_skip_unknown_fields is set to 1. Otherwise, the first row will be skipped.
JSONCompactStringsEachRowWithNamesAndTypes
Differs from JSONCompactStringsEachRow
in that it also prints two header rows with column names and types, similar to TabSeparatedWithNamesAndTypes.
If setting input_format_with_names_use_header is set to 1, the columns from input data will be mapped to the columns from the table by their names, columns with unknown names will be skipped if setting input_format_skip_unknown_fields is set to 1. Otherwise, the first row will be skipped. If setting input_format_with_types_use_header is set to 1, the types from input data will be compared with the types of the corresponding columns from the table. Otherwise, the second row will be skipped.
["num", "str", "arr"]
["Int32", "String", "Array(UInt8)"]
[42, "hello", [0,1]]
[43, "hello", [0,1,2]]
[44, "hello", [0,1,2,3]]
JSONObjectEachRow
In this format, all data is represented as a single JSON Object, each row is represented as a separate field of this object similar to JSONEachRow format.
Example:
{
"row_1": {"num": 42, "str": "hello", "arr": [0,1]},
"row_2": {"num": 43, "str": "hello", "arr": [0,1,2]},
"row_3": {"num": 44, "str": "hello", "arr": [0,1,2,3]}
}
To use an object name as a column value you can use the special setting format_json_object_each_row_column_for_object_name. The value of this setting is set to the name of a column, that is used as JSON key for a row in the resulting object. Examples:
For output:
Let's say we have the table test
with two columns:
┌─object_name─┬─number─┐
│ first_obj │ 1 │
│ second_obj │ 2 │
│ third_obj │ 3 │
└─────────────┴────────┘
Let's output it in JSONObjectEachRow
format and use format_json_object_each_row_column_for_object_name
setting:
select * from test settings format_json_object_each_row_column_for_object_name='object_name'
The output:
{
"first_obj": {"number": 1},
"second_obj": {"number": 2},
"third_obj": {"number": 3}
}
For input:
Let's say we stored output from the previous example in a file named data.json
:
select * from file('data.json', JSONObjectEachRow, 'object_name String, number UInt64') settings format_json_object_each_row_column_for_object_name='object_name'
┌─object_name─┬─number─┐
│ first_obj │ 1 │
│ second_obj │ 2 │
│ third_obj │ 3 │
└─────────────┴────────┘
It also works in schema inference:
desc file('data.json', JSONObjectEachRow) settings format_json_object_each_row_column_for_object_name='object_name'
┌─name────────┬─type────────────┐
│ object_name │ String │
│ number │ Nullable(Int64) │
└─────────────┴─────────────────┘
Inserting Data
INSERT INTO UserActivity FORMAT JSONEachRow {"PageViews":5, "UserID":"4324182021466249494", "Duration":146,"Sign":-1} {"UserID":"4324182021466249494","PageViews":6,"Duration":185,"Sign":1}
ClickHouse allows:
- Any order of key-value pairs in the object.
- Omitting some values.
ClickHouse ignores spaces between elements and commas after the objects. You can pass all the objects in one line. You do not have to separate them with line breaks.
Omitted values processing
ClickHouse substitutes omitted values with the default values for the corresponding data types.
If DEFAULT expr
is specified, ClickHouse uses different substitution rules depending on the input_format_defaults_for_omitted_fields setting.
Consider the following table:
CREATE TABLE IF NOT EXISTS example_table
(
x UInt32,
a DEFAULT x * 2
) ENGINE = Memory;
- If
input_format_defaults_for_omitted_fields = 0
, then the default value forx
anda
equals0
(as the default value for theUInt32
data type). - If
input_format_defaults_for_omitted_fields = 1
, then the default value forx
equals0
, but the default value ofa
equalsx * 2
.
When inserting data with input_format_defaults_for_omitted_fields = 1
, ClickHouse consumes more computational resources, compared to insertion with input_format_defaults_for_omitted_fields = 0
.
Selecting Data
Consider the UserActivity
table as an example:
┌──────────────UserID─┬─PageViews─┬─Duration─┬─Sign─┐
│ 4324182021466249494 │ 5 │ 146 │ -1 │
│ 4324182021466249494 │ 6 │ 185 │ 1 │
└─────────────────────┴───────────┴──────────┴──────┘
The query SELECT * FROM UserActivity FORMAT JSONEachRow
returns:
{"UserID":"4324182021466249494","PageViews":5,"Duration":146,"Sign":-1}
{"UserID":"4324182021466249494","PageViews":6,"Duration":185,"Sign":1}
Unlike the JSON format, there is no substitution of invalid UTF-8 sequences. Values are escaped in the same way as for JSON
.
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.
Usage of Nested Structures
If you have a table with Nested data type columns, you can insert JSON data with the same structure. Enable this feature with the input_format_import_nested_json setting.
For example, consider the following table:
CREATE TABLE json_each_row_nested (n Nested (s String, i Int32) ) ENGINE = Memory
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:
INSERT INTO json_each_row_nested FORMAT JSONEachRow {"n.s": ["abc", "def"], "n.i": [1, 23]}
To insert data as a hierarchical JSON object, set input_format_import_nested_json=1.
{
"n": {
"s": ["abc", "def"],
"i": [1, 23]
}
}
Without this setting, ClickHouse throws an exception.
SELECT name, value FROM system.settings WHERE name = 'input_format_import_nested_json'
┌─name────────────────────────────┬─value─┐
│ input_format_import_nested_json │ 0 │
└─────────────────────────────────┴───────┘
INSERT INTO json_each_row_nested FORMAT JSONEachRow {"n": {"s": ["abc", "def"], "i": [1, 23]}}
Code: 117. DB::Exception: Unknown field found while parsing JSONEachRow format: n: (at row 1)
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
┌─n.s───────────┬─n.i────┐
│ ['abc','def'] │ [1,23] │