CAST converts a value or column to a different data type in ClickHouse, enabling accurate comparisons, arithmetic, and joins.
CAST converts an expression to the specified data type so functions, comparisons, and joins work without type errors.
Use either CAST(expr AS type)
or functional cast(expr,'type')
. Both forms accept the same data-type keywords.
Functional style is easier to build in dynamic SQL strings, while ANSI style improves readability in static queries.
Convert an Orders.order_date
string to DateTime
for date math:
SELECT CAST(order_date AS DateTime) AS order_ts
FROM Orders;
Specify precision and scale explicitly:
SELECT CAST(total_amount AS Decimal(18,2)) AS amount
FROM Orders;
Yes—wrap the target type with Nullable()
:
SELECT CAST(stock AS Nullable(Int32)) AS stock_nullable
FROM Products;
Combine with arithmetic to avoid implicit casts:
SELECT customer_id,
total_amount / cast(quantity,'Float64') AS unit_price
FROM Orders o
JOIN OrderItems i ON i.order_id = o.id;
Cast early in CTEs, validate source data with isValidUTF8
or regex, and always document precision when using Decimal
.
CAST is vectorized and generally fast, but excessive casting in large queries can add noticeable CPU overhead. Cast once in a subquery or materialized view when possible.
Yes. Use CAST(array_column AS Array(Int32))
or cast(nested_col,'Tuple(name String, qty Int32)')
to convert complex types.