[ClickHouse Practice] Applying functions to multiple columns

When writing SQL, you may sometimes want to apply the same function to multiple columns, which often requires duplicating code and having to list all columns, for example:

SELECT
    *,
    formatReadableSize(read_bytes) AS read_bytes_readable,
    formatReadableSize(written_bytes) AS written_bytes_readable,
    formatReadableSize(result_bytes) AS result_bytes_readable
FROM system.query_log
WHERE query_id = '56c3c260-34bc-4e35-88e7-07d50a04e8f9'

This can lead to very long and difficult to maintain query statements, especially as the query size grows. SELECT ... EXCEPTAt this point syntax can be used , eg SELECT * EXCEPT (read_bytes, written_bytes, result_bytes). This syntax allows a provided subset of columns to be dropped from the result. You can also use COLUMNSexpressions to select the strings that are commonly included in the column names, for example, COLUMNS('bytes')will match to the three columns of read_bytes, written_bytesand , similar to the usage of like, and finally use modifiers to apply the function to each column previously selected, for example .result_bytesAPPLYAPPLY formatReadableSize

The full query looks like this:

SELECT
    * EXCEPT (read_bytes, written_bytes, result_bytes),
    COLUMNS('bytes') APPLY formatReadableSize
FROM system.query_log
WHERE query_id = '56c3c260-34bc-4e35-88e7-07d50a04e8f9'

This SQL is equivalent to the first SQL.

Guess you like

Origin blog.csdn.net/weixin_39992480/article/details/128009187