Dynamic column selection
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.
We're going to learn how to use this feature with help from the New York taxis dataset, which you can also find in the ClickHouse SQL playground.
Selecting columns that match a pattern
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:
This query returns the first 10 rows, but only for columns whose names match the pattern .*_amount
(any characters followed by "_amount").
Let’s say we also want to return columns that contain the terms fee
or tax
.
We can update the regular expression to include those:
Selecting multiple patterns
We can combine multiple column patterns in a single query:
Apply functions to all columns
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:
Or maybe, we’d like to see the average instead:
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:
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:
Replacing columns
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.
Excluding columns
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: