Search code examples
sqlarraysenumsclickhouse

Array of enums type in ClickHouse


In ClickHouse 21.4 I created a table with array of enums column:

CREATE TABLE test_array_enum (
    id String,
    fixation_at DateTime64(3, 'UTC'),
    types Array(
        Enum(
            'FIRST_TYPE' = 1, 'SECOND_TYPE' = 2, 'THIRD_TYPE' = 3,
            'FOURTH_TYPE' = 4
        )
    )
)
ENGINE = ReplacingMergeTree
ORDER BY (fixation_at, id);

Fill some data:

INSERT INTO test_array_enum (id, fixation_at, types) VALUES ('1', now64(), []),
                                                            ('2', now64(), ['FIRST_TYPE']),
                                                            ('3', now64(), ['SECOND_TYPE', 'THIRD_TYPE']),
                                                            ('4', now64(), ['FOURTH_TYPE']);

I want to filter data by types column, query returns 0 rows:

SELECT *
FROM test_array_enum
WHERE hasAny(types, ['SECOND_TYPE', 'THIRD_TYPE']);

It works fine with Int values:

SELECT *
FROM test_array_enum
WHERE hasAny(types, [2, 3]);

Is there a way to filter data by string values of enum?


Solution

  • Try this query:

    SELECT *
    FROM test_array_enum
    WHERE arrayFirstIndex(x -> x = 'SECOND_TYPE' OR x = 'THIRD_TYPE', types) > 0
    
    /*
    ┌─id─┬─────────────fixation_at─┬─types────────────────────────┐
    │ 3  │ 2021-07-08 02:11:21.238 │ ['SECOND_TYPE','THIRD_TYPE'] │
    └────┴─────────────────────────┴──────────────────────────────┘
    */