Dynamic column selection is a powerful but underutilized ClickHouse feature that allows you to select columns using regular expressions instead of naming each column individually. You can also apply functions to matching columns using the APPLY modifier, making it incredibly useful for data analysis and transformation tasks.
Let's start with a common scenario: selecting only the columns that contain _amount from the NYC taxi dataset. Instead of manually typing each column name, we can use the COLUMNS expression with a regular expression:
FROM nyc_taxi.trips
SELECT COLUMNS('.*_amount')
LIMIT 10;
We can also use the APPLY modifier to apply functions across every column.
For example, if we wanted to find the maximum value of each of those columns, we could run the following query:
SELECT COLUMNS('.*_amount|fee|tax') APPLY(max)
FROM nyc_taxi.trips;
Those values contain a lot of decimal places, but luckily we can fix that by chaining functions. In this case, we’ll apply the avg function, followed by the round function:
SELECT COLUMNS('.*_amount|fee|tax') APPLY(avg) APPLY(round)
FROM nyc_taxi.trips;
But that rounds the averages to whole numbers. If we want to round to, say, 2 decimal places, we can do that as well. As well as taking in functions, the APPLY modifier accepts a lambda, which gives us the flexibility to have the round function round our average values to 2 decimal places:
SELECT COLUMNS('.*_amount|fee|tax') APPLY(avg) APPLY(x -> round(x, 2))
FROM nyc_taxi.trips;
So far so good. But let’s say we want to adjust one of the values, while leaving the other ones as they are. For example, maybe we want to double the total amount and divide the MTA tax by 1.1. We can do that by using the REPLACE modifier, which will replace a column while leaving the other ones as they are.
FROM nyc_taxi.trips
SELECT
COLUMNS('.*_amount|fee|tax')
REPLACE(
total_amount*2 AS total_amount,
mta_tax/1.1 AS mta_tax
)
APPLY(avg)
APPLY(col -> round(col, 2));
We can also choose to exclude a field by using the EXCEPT modifier. For example, to remove the tolls_amount column, we would write the following query:
FROM nyc_taxi.trips
SELECT
COLUMNS('.*_amount|fee|tax') EXCEPT(tolls_amount)
REPLACE(
total_amount*2 AS total_amount,
mta_tax/1.1 AS mta_tax
)
APPLY(avg)
APPLY(col -> round(col, 2));