Skip to main content

Casting

To cast, use the infix operator AS. Hamelin uses the AS operator for explicit type casting. You write the value, then AS, then the type you want.

The two most common reasons to cast are:

  • Casting variant to explicit types after parsing JSON
  • Casting types to string to concatenate them together

Basic syntax

Cast a value by putting AS between the value and the target type:

| SET x = 5 AS double

This creates a double-precision value instead of an integer.

Why AS for casting?

You'll use explicit casting often, especially when declaring literals to influence type inference. We wanted something terse. Using AS for assignment confuses people (the order seems backwards). This frees up AS for casting, which reads cleanly: treat this one thing as another type.

How it works

The AS operator translates explicit cast expressions into the generated code. We often actually translate to try_cast() in order to make sure the query doesn't crash.

Hamelin delegates implicit casting to the underlying engine — if you assign a value to a typed field or pass it to a function that expects a different type, the engine decides whether and how to cast the value.

Common casting examples

String conversions

Convert values to strings for display or storage:

FROM events
| SELECT
user_id_str = user_id AS string,
timestamp_str = timestamp AS string,
status_display = status_code AS string

Numeric conversions

Convert between different numeric types or from strings to numbers:

FROM logs
| SELECT
status_code = response_code AS integer,
response_time = response_time_str AS double,
user_count = total_users AS integer

Boolean conversions

Convert various values to boolean types:

FROM user_data
| SELECT
user_id,
is_active = status_flag AS boolean,
has_permissions = permission_level AS boolean

Type inference with casting

You can influence type inference in variable declarations by casting literals:

FROM events
| SET
threshold = 100 AS double,
max_retries = 5 AS integer,
default_timeout = 30.0
| WHERE response_time > threshold

Note that 30.0 is already a double (bare decimal literals are doubles), so no cast is needed. The 100 AS double cast is useful because 100 alone would be an integer.

Complex type casting

Array casting

Cast arrays to specific element types:

FROM json_data
| SELECT
tags = tag_list AS array(string),
scores = score_array AS array(double)

Struct casting

Cast structured data to specific field types:

FROM structured_data
| SELECT
user_info = user_data AS {name: string, email: string},
coordinates = location AS {x: double, y: double}