Skip to main content

Tuple(t1, T2, …)

A tuple of elements, each having an individual type.

Tuples are used for temporary column grouping. Columns can be grouped when an IN expression is used in a query, and for specifying certain formal parameters of lambda functions. For more information, see the sections IN operators and Higher order functions.

Tuples can be the result of a query. In this case, for text formats other than JSON, values are comma-separated in brackets. In JSON formats, tuples are output as arrays (in square brackets).

Creating a Tuple​

You can use a function to create a tuple:

tuple(T1, T2, ...)

Example of creating a tuple:

SELECT tuple(1,'a') AS x, toTypeName(x)
β”Œβ”€x───────┬─toTypeName(tuple(1, 'a'))─┐
β”‚ (1,'a') β”‚ Tuple(UInt8, String) β”‚

Working with Data Types​

When creating a tuple on the fly, ClickHouse automatically detects the type of each argument as the minimum of the types which can store the argument value. If the argument is NULL, the type of the tuple element is Nullable.

Example of automatic data type detection:

SELECT tuple(1, NULL) AS x, toTypeName(x)
β”Œβ”€x────────┬─toTypeName(tuple(1, NULL))──────┐
β”‚ (1,NULL) β”‚ Tuple(UInt8, Nullable(Nothing)) β”‚

Addressing Tuple Elements​

It is possible to read elements of named tuples using indexes and names:

CREATE TABLE named_tuples (`a` Tuple(s String, i Int64)) ENGINE = Memory;

INSERT INTO named_tuples VALUES (('y', 10)), (('x',-10));

SELECT a.s FROM named_tuples;

SELECT a.2 FROM named_tuples;


β”‚ y β”‚
β”‚ x β”‚

β”Œβ”€tupleElement(a, 2)─┐
β”‚ 10 β”‚
β”‚ -10 β”‚

Original article