View a markdown version of this page

Expressions and operators in DuckDB - Amazon Athena

Expressions and operators in DuckDB

Use expressions to compute values in a query: in the select list, in the WHERE, GROUP BY, HAVING, and ORDER BY clauses, and as function arguments. This topic describes the expression syntax of DuckDB that you write with SQL keywords and brackets instead of calling a function. It covers conditional expressions, casts, range and membership tests, NULL tests, logical operators, lambda functions, and list and struct values.

Most expressions return NULL when an input is NULL. Each section describes the exceptions. IS NULL, IS DISTINCT FROM, COALESCE, and CASE are made for handling NULL values, and AND and OR can return true or false when one operand is NULL.

The examples use literal values and inline VALUES lists, so you can run them in any database without creating a table. In query results, a list appears as [1, 2, 3] and a struct as {'region': east, 'amount': 120.5}. String values inside lists and structs appear without quotation marks.

For more information about functions and about the arithmetic, comparison, and string operators, see Functions and operators in DuckDB.

CASE expressions

A CASE expression tests its WHEN branches in order and returns the THEN result of the first branch that matches. The searched form tests a Boolean condition in each branch. The simple form compares one expression with the value in each branch, and a branch matches when the two values are equal.

If no branch matches, the expression returns the ELSE result, or NULL when there is no ELSE clause. The THEN and ELSE results are converted to one common type, which is the type of the CASE expression.

Syntax

CASE WHEN condition THEN result [ WHEN condition THEN result [ ... ] ] [ ELSE default ] END CASE expression WHEN value THEN result [ WHEN value THEN result [ ... ] ] [ ELSE default ] END

In the syntax, replace each placeholder as follows:

condition

The condition of a branch in the searched form, as a Boolean expression. The branch matches when condition is true, and does not match when it is false or NULL.

expression

The value that the simple form compares with the value of each branch.

value

The value to compare with expression in a branch of the simple form. The branch matches when the two values are equal.

result

The value that the CASE expression returns when the branch matches. You can repeat the WHEN and THEN pair for as many branches as you need.

default

The value to return when no branch matches. Without an ELSE clause, the expression returns NULL. This parameter is optional.

Examples

The following SQL query uses the searched form to label each number as negative, zero, or positive.

SELECT x, CASE WHEN x < 0 THEN 'negative' WHEN x = 0 THEN 'zero' ELSE 'positive' END AS sign_label FROM (VALUES (-5), (0), (7)) AS t(x) ORDER BY x

The query returns the following results.

x sign_label

-5

negative

0

zero

7

positive

The following SQL query uses the simple form without an ELSE clause. The value 3 matches no branch, so the result is NULL.

SELECT x, CASE x WHEN 1 THEN 'one' WHEN 2 THEN 'two' END AS word FROM (VALUES (1), (2), (3)) AS t(x) ORDER BY x

The query returns the following results.

x word

1

one

2

two

3

NULL

The following SQL query shows that a WHEN NULL branch of the simple form does not match a NULL value, while the searched form with IS NULL does.

SELECT id, CASE status WHEN NULL THEN 'missing' ELSE 'present' END AS simple_form, CASE WHEN status IS NULL THEN 'missing' ELSE 'present' END AS searched_form FROM (VALUES (1, 'shipped'), (2, NULL)) AS t(id, status) ORDER BY id

The query returns the following results.

id simple_form searched_form

1

present

present

2

present

missing

Considerations

The simple form compares values in the same way as =, so a WHEN NULL branch never matches, not even when expression is NULL. To test for NULL, use the searched form with WHEN expression IS NULL.

Only the first branch that matches counts, so put the most specific conditions first.

CAST, TRY_CAST, and the :: operator

CAST converts a value to the data type that you name. expression::type is a shorter way to write the same cast. If a value cannot be converted, for example the string 'abc' to INTEGER or the number 300 to TINYINT, the query fails.

TRY_CAST converts a value in the same way, but returns NULL for a value that cannot be converted, and the query continues. A cast of NULL returns NULL of the target type.

You can cast to any type that DuckDB supports, including list types such as INTEGER[] and struct types such as STRUCT(customer VARCHAR, amount DOUBLE). A cast to a list type converts each element.

A cast from text to JSON parses the text, and the query fails when the text is not valid JSON. For more information about the JSON type, see JSON type.

Syntax

CAST( expression AS type ) expression::type TRY_CAST( expression AS type )

In the syntax, replace each placeholder as follows:

expression

The value to convert.

type

The data type to convert to, such as INTEGER, DECIMAL(10,2), DATE, VARCHAR, or INTEGER[].

Examples

The following SQL query converts a string to INTEGER with CAST, and uses :: to convert a string to DATE and a number to VARCHAR.

SELECT CAST('42' AS INTEGER) + 1 AS next_number, '2026-10-01'::DATE + 1 AS next_day, 42::VARCHAR || '!' AS label

The query returns the following result.

next_number next_day label

43

2026-10-02

42!

The following SQL query uses TRY_CAST on four strings. The cast ignores a trailing space, reads exponent notation, and returns NULL for a string that is not a number.

SELECT TRY_CAST('42' AS INTEGER) AS digits, TRY_CAST('12 ' AS INTEGER) AS trailing_space, TRY_CAST('1e2' AS INTEGER) AS exponent, TRY_CAST('abc' AS INTEGER) AS not_a_number

The query returns the following result.

digits trailing_space exponent not_a_number

42

12

100

NULL

The following SQL query casts values that are halfway between two integers to INTEGER. A DOUBLE half rounds to the even integer, a DECIMAL half rounds away from zero, and round before the cast rounds a DOUBLE half away from zero.

SELECT CAST(2.5E0 AS INTEGER) AS double_2_5, CAST(3.5E0 AS INTEGER) AS double_3_5, CAST(2.5 AS INTEGER) AS decimal_2_5, CAST(round(2.5E0) AS INTEGER) AS rounded_first

The query returns the following result.

double_2_5 double_3_5 decimal_2_5 rounded_first

2

4

3

3

The following SQL query shows that a bare DECIMAL type, written without a precision and scale, keeps three digits after the decimal point, and that DECIMAL(10,4) keeps four.

SELECT CAST(1.23456 AS DECIMAL) AS bare_decimal, typeof( CAST(1.23456 AS DECIMAL) ) AS bare_decimal_type, CAST(1.23456 AS DECIMAL(10,4)) AS decimal_10_4

The query returns the following result.

bare_decimal bare_decimal_type decimal_10_4

1.235

DECIMAL(18,3)

1.2346

The following SQL query casts a list of strings to a list of integers, and uses parentheses to cast a negative number with ::.

SELECT ['1', '2', '3']::INTEGER[] AS numbers, (-1)::VARCHAR AS negative_text, typeof((-1)::VARCHAR) AS negative_text_type

The query returns the following result.

numbers negative_text negative_text_type

[1, 2, 3]

-1

VARCHAR

The following SQL query casts text to JSON, which parses the text as a JSON array, and compares it with to_json, which stores the text as a JSON string.

SELECT CAST('[1,2]' AS JSON) AS parsed, json_type(CAST('[1,2]' AS JSON)) AS parsed_kind, to_json('[1,2]') AS json_string

The query returns the following result.

parsed parsed_kind json_string

[1,2]

ARRAY

"[1,2]"

The following SQL query uses CAST on a string that has a space before and after the digits. The cast ignores the spaces, so the query does not fail.

SELECT CAST(' 12 ' AS INTEGER) AS spaces_around, CAST(' 12 ' AS INTEGER) + 1 AS plus_one

The query returns the following result.

spaces_around plus_one

12

13

Considerations

:: binds more tightly than arithmetic operators and a leading minus sign, so it applies only to the value directly before it. For example, -1::VARCHAR fails, because it casts 1 to VARCHAR and then tries to negate a string. Write (-1)::VARCHAR or CAST(-1 AS VARCHAR) instead.

A bare DECIMAL type is DECIMAL(18,3), so CAST(1.23456 AS DECIMAL) returns 1.235. Give the precision and scale that you need, such as DECIMAL(10,4). For more information about the DECIMAL type, including how its default precision and scale differ from Athena engine version 3, see Fixed-point decimal type.

A cast from DOUBLE or REAL to an integer type rounds a value that is halfway between two integers to the even integer. For example, 2.5E0 becomes 2 and 3.5E0 becomes 4. A cast from DECIMAL rounds halves away from zero, so 2.5 becomes 3. To round halves away from zero for a DOUBLE value, use CAST(round(x) AS BIGINT).

A cast from a string to a number ignores spaces before and after the digits and accepts exponent notation, so '12 ' becomes 12 and '1e2' becomes 100.

Differences from Athena engine version 3

In Athena engine version 3, a cast from DOUBLE or REAL to an integer type rounds halves away from zero, so CAST(2.5E0 AS BIGINT) returns 3. In DuckDB, it rounds halves to the even integer and returns 2. To get the Athena engine version 3 result, use CAST(round(x) AS BIGINT). The same applies to INTEGER, SMALLINT, and TINYINT. For more information about differences that change results, see Differences that change results without an error.

In Athena engine version 3, TRY_CAST('12 ' AS INTEGER) and TRY_CAST('1e2' AS INTEGER) return NULL. In DuckDB, they return 12 and 100. To return NULL for such strings, use CASE WHEN regexp_full_match(s, '[+-]?[0-9]+') THEN TRY_CAST(s AS INTEGER) END. This form accepts only the ASCII digits 0 to 9, while Athena engine version 3 also reads digits from other scripts.

In Athena engine version 3, CAST(' 12 ' AS INTEGER) makes the query fail, because the string has spaces around the number. In DuckDB, the cast ignores the spaces and returns 12.

In Athena engine version 3, CAST('[1,2]' AS JSON) returns the JSON string "[1,2]". In DuckDB, a cast from text to JSON parses the text, so the same cast returns the JSON array [1,2]. To get the Athena engine version 3 result, use to_json(s).

In Athena engine version 3, CAST('abc' AS JSON) returns a JSON string. In DuckDB, the cast fails, because abc is not valid JSON text. Use to_json('abc') instead.

TRY expressions

TRY evaluates an expression and returns its result. If the expression causes an error for a row, such as a failed conversion or an integer division by zero, TRY returns NULL for that row, and the query continues.

Use TRY to read data in which some values are not valid, such as dates written in more than one format. To convert a value to another type, you can also use TRY_CAST.

Syntax

TRY( expression )

In the syntax, replace each placeholder as follows:

expression

The expression to evaluate. It can use scalar functions and operators.

Examples

The following SQL query divides 100 by each value with the integer division operator //. For the row where the divisor is 0, TRY returns NULL instead of failing the query.

SELECT x, TRY(100 // x) AS quotient FROM (VALUES (1, 4), (2, 0)) AS t(id, x) ORDER BY id

The query returns the following results.

x quotient

4

25

0

NULL

The following SQL query parses strings as dates in the format YYYY-MM-DD. The second string has another format, so TRY returns NULL for it.

SELECT x, CAST( TRY(strptime(x, '%Y-%m-%d')) AS DATE ) AS order_date FROM (VALUES (1, '2026-10-01'), (2, '10/01/2026') ) AS t(id, x) ORDER BY id

The query returns the following results.

x order_date

2026-10-01

2026-10-01

10/01/2026

NULL

The following SQL query shows that TRY does not change the result of 1 / 0, which is an infinite DOUBLE value and not an error. It also shows that TRY with // returns NULL.

SELECT isinf(TRY(1 / 0)) AS still_infinite, TRY(1 // 0) AS integer_division

The query returns the following result.

still_infinite integer_division

true

NULL

Considerations

You cannot use TRY with a function whose result varies from call to call, such as random(), or with an aggregate function such as sum. Such a query fails.

TRY handles errors that come from the values in the data. It does not handle errors in the query itself, such as a column that does not exist or an operator that cannot take the types that you pass. Those queries still fail.

TRY does not change the result of an expression that returns a special value instead of an error. For example, 1 / 0 returns positive infinity, which query results show as inf, so TRY(1 / 0) also returns inf. To get NULL for a division by zero, use TRY(x // y) or x / NULLIF(y, 0).

Differences from Athena engine version 3

In Athena engine version 3, an integer division by zero fails, so TRY(1 / 0) returns NULL. In DuckDB, / returns a DOUBLE, and 1 / 0 returns positive infinity, shown as inf, without an error, so TRY does not change the result. To get NULL, use TRY(x // y) or x / NULLIF(y, 0).

BETWEEN operator

x BETWEEN low AND high returns the same result as x >= low AND x <= high, so the range includes both low and high. NOT BETWEEN returns the opposite result.

You can use BETWEEN with any values that you can compare, such as numbers, strings, dates, and timestamps. NULL values follow the rules of AND, so when x is NULL, the result is NULL.

Syntax

x [ NOT ] BETWEEN low AND high

In the syntax, replace each placeholder as follows:

x

The value to test.

low

The lower end of the range.

high

The upper end of the range.

Examples

The following SQL query tests each value against the range from 2 through 4. Both ends are in the range, and both tests return NULL for a NULL value.

SELECT x, x BETWEEN 2 AND 4 AS in_range, x NOT BETWEEN 2 AND 4 AS outside_range FROM (VALUES (1, 1), (2, 2), (3, 4), (4, 5), (5, NULL) ) AS t(id, x) ORDER BY id

The query returns the following results.

x in_range outside_range

1

false

true

2

true

false

4

true

false

5

false

true

NULL

NULL

NULL

The following SQL query tests a date range, a range whose bounds are in the wrong order, and a string range.

SELECT DATE '2026-10-02' BETWEEN DATE '2026-10-01' AND DATE '2026-10-31' AS in_october, 3 BETWEEN 5 AND 1 AS reversed_bounds, 'banana' BETWEEN 'a' AND 'b' AS banana_a_to_b

The query returns the following result.

in_october reversed_bounds banana_a_to_b

true

false

false

Considerations

BETWEEN does not swap the bounds. If low is greater than high, no value is in the range, so 3 BETWEEN 5 AND 1 returns false.

Strings compare character by character and are case-sensitive. 'banana' BETWEEN 'a' AND 'b' returns false, because 'banana' sorts after 'b'. To find the strings that start with a or b, write s >= 'a' AND s < 'c'.

For timestamps, the range ends exactly at high, so a range that ends at TIMESTAMP '2026-10-31' leaves out every timestamp on October 31 after midnight. To select a whole day, compare with the start of the next day, as in ts >= TIMESTAMP '2026-10-01' AND ts < TIMESTAMP '2026-10-02'.

IN operator

x IN (value [, ...]) returns true when x equals at least one of the listed values. The form x IN (subquery) compares x with each row of a subquery that returns one column. NOT IN returns the opposite result.

IN compares values in the same way as =, including for NULL values. When x equals no value and the list or the subquery contains a NULL, the result is NULL, not false. When x is NULL, the result is NULL, except when the subquery returns no rows: then IN returns false and NOT IN returns true.

Syntax

x [ NOT ] IN ( value [, ...] ) x [ NOT ] IN ( subquery )

In the syntax, replace each placeholder as follows:

x

The value to look for.

value

A value to compare with x. All values must have types that can be compared with x.

subquery

A SELECT statement that returns one column.

Examples

The following SQL query tests values against a list. The last test finds no match in a list that contains NULL, so its result is NULL.

SELECT 2 IN (1, 2, 3) AS found, 4 IN (1, 2, 3) AS not_found, 4 NOT IN (1, 2, 3) AS not_in, 4 IN (1, 2, NULL) AS no_match_with_null

The query returns the following result.

found not_found not_in no_match_with_null

true

false

true

NULL

The following SQL query keeps the rows whose id appears in the result of a subquery.

SELECT id FROM (VALUES (1), (2), (3), (4)) AS t(id) WHERE id IN ( SELECT x FROM (VALUES (2), (4), (6)) AS s(x) ) ORDER BY id

The query returns the following results.

id

2

4

The following SQL query shows NOT IN with a subquery that returns a NULL. The value 1 is not in the subquery, but the result is NULL, not true.

SELECT id, id NOT IN ( SELECT x FROM (VALUES (2), (NULL)) AS s(x) ) AS not_in FROM (VALUES (1), (2)) AS t(id) ORDER BY id

The query returns the following results.

id not_in

1

NULL

2

false

Considerations

Because of the NULL rule, NOT IN is never true when the list or the subquery contains a NULL, so a WHERE x NOT IN (subquery) filter keeps no rows. To leave NULL values out, add WHERE column IS NOT NULL to the subquery, or use NOT EXISTS.

For more information about subqueries, see Subqueries.

IS NULL and IS NOT NULL

IS NULL returns true when a value is NULL, and IS NOT NULL returns true when it is not. Both return true or false, never NULL.

Do not test for NULL with = or <>. A comparison with NULL returns NULL, so a filter such as WHERE x = NULL keeps no rows.

DuckDB also accepts the shorter forms expression ISNULL and expression NOTNULL.

Syntax

expression IS [ NOT ] NULL expression { ISNULL | NOTNULL }

Examples

The following SQL query tests a value and a NULL with IS NULL, IS NOT NULL, and =. The = comparison returns NULL in both rows.

SELECT x, x IS NULL AS is_null, x IS NOT NULL AS is_not_null, x = NULL AS equals_null FROM (VALUES (1, 10), (2, NULL)) AS t(id, x) ORDER BY id

The query returns the following results.

x is_null is_not_null equals_null

10

false

true

NULL

NULL

true

false

NULL

The following SQL query keeps only the rows whose status is not NULL.

SELECT id FROM (VALUES (1, 'shipped'), (2, NULL), (3, 'open') ) AS t(id, status) WHERE status IS NOT NULL ORDER BY id

The query returns the following results.

id

1

3

The following SQL query uses the shorter forms ISNULL and NOTNULL, which return the same results as IS NULL and IS NOT NULL.

SELECT x, x ISNULL AS is_null, x NOTNULL AS is_not_null FROM (VALUES (1, 10), (2, NULL)) AS t(id, x) ORDER BY id

The query returns the following results.

x is_null is_not_null

10

false

true

NULL

true

false

IS DISTINCT FROM and IS NOT DISTINCT FROM

IS DISTINCT FROM works like <>, and IS NOT DISTINCT FROM works like =, except in how they treat NULL. Two NULL values count as the same, and a NULL value counts as different from every other value. Both return true or false, never NULL.

For more information about these operators, see IS DISTINCT FROM and IS NOT DISTINCT FROM operators.

Syntax

x IS [ NOT ] DISTINCT FROM y

Examples

The following SQL query compares two columns that can be NULL with = and with IS NOT DISTINCT FROM.

SELECT a, b, a = b AS equal, a IS NOT DISTINCT FROM b AS not_distinct FROM (VALUES (1, 1, 1), (2, 1, NULL), (3, NULL, NULL) ) AS t(id, a, b) ORDER BY id

The query returns the following results.

a b equal not_distinct

1

1

true

true

1

NULL

NULL

false

NULL

NULL

NULL

true

Logical operators AND, OR, and NOT

AND returns true when both operands are true. OR returns true when at least one operand is true. NOT reverses a Boolean value.

The operators use three-valued logic, in which NULL stands for an unknown value. The result is NULL only when it depends on the unknown value. For example, false AND NULL is false and true OR NULL is true, whatever the unknown value is. However, true AND NULL and false OR NULL are NULL, and NOT of NULL is NULL.

NOT binds more tightly than AND, and AND binds more tightly than OR. Use parentheses to group conditions in another order.

IS TRUE, IS FALSE, IS NOT TRUE, and IS NOT FALSE test a Boolean value and never return NULL. For example, NULL IS NOT TRUE returns true.

Syntax

a AND b a OR b NOT a a IS [ NOT ] { TRUE | FALSE }

Examples

The following SQL query lists every combination of true, false, and NULL for two operands, with the results of AND, OR, and NOT.

SELECT a, b, a AND b AS a_and_b, a OR b AS a_or_b, NOT a AS not_a FROM (VALUES (true), (false), (NULL)) AS x(a), (VALUES (true), (false), (NULL)) AS y(b) ORDER BY a DESC NULLS LAST, b DESC NULLS LAST

The query returns the following results.

a b a_and_b a_or_b not_a

true

true

true

true

false

true

false

false

true

false

true

NULL

NULL

true

false

false

true

false

true

true

false

false

false

false

true

false

NULL

false

NULL

true

NULL

true

NULL

true

NULL

NULL

false

false

NULL

NULL

NULL

NULL

NULL

NULL

NULL

The following SQL query compares NOT with IS NOT TRUE. For the NULL row, NOT returns NULL, and IS NOT TRUE returns true.

SELECT id, NOT flag AS not_flag, flag IS NOT TRUE AS flag_is_not_true FROM (VALUES (1, true), (2, false), (3, NULL) ) AS t(id, flag) ORDER BY id

The query returns the following results.

id not_flag flag_is_not_true

1

false

false

2

true

true

3

NULL

true

The following SQL query shows that AND is evaluated before OR unless parentheses group the conditions another way.

SELECT true OR true AND false AS and_first, (true OR true) AND false AS or_first

The query returns the following result.

and_first or_first

true

false

Considerations

A WHERE, HAVING, or QUALIFY clause keeps a row only when its condition is true, so it leaves out the rows where the condition is NULL. For example, WHERE NOT flag leaves out both the rows where flag is true and the rows where it is NULL. To keep the NULL rows too, write WHERE flag IS NOT TRUE.

COALESCE

COALESCE reads its arguments from left to right and returns the first one that is not NULL. If every argument is NULL, it returns NULL. Use it to replace NULL with a default value, or to choose the first available value from several columns.

The arguments are converted to one common type, which is the type of the result.

Syntax

COALESCE( value [, ...] )

In the syntax, replace each placeholder as follows:

value

The values to check, from left to right. Give one or more values whose types can be converted to one common type.

Examples

The following SQL query returns the first value that is not NULL, replaces NULL with 0, and shows that COALESCE of only NULL values is NULL.

SELECT coalesce( NULL, NULL, 'third', 'fourth' ) AS first_value, coalesce(NULL, 0) AS default_zero, coalesce(NULL, NULL) IS NULL AS all_null

The query returns the following result.

first_value default_zero all_null

third

0

true

The following SQL query shows each person's nickname, or the full name when there is no nickname, or unknown when both are NULL.

SELECT id, coalesce( nickname, full_name, 'unknown' ) AS display_name FROM (VALUES (1, 'al', 'alice'), (2, NULL, 'bob'), (3, NULL, NULL) ) AS t(id, nickname, full_name) ORDER BY id

The query returns the following results.

id display_name

1

al

2

bob

3

unknown

NULLIF

NULLIF(a, b) returns NULL when a equals b, and returns a otherwise. It returns the same result as CASE WHEN a = b THEN NULL ELSE a END.

Use NULLIF to turn a placeholder value, such as 0 or an empty string, into NULL. For example, x / NULLIF(y, 0) returns NULL when y is 0, whereas x / y returns a special value: inf or -inf, or nan when x is also 0.

For more information about the nullif function, see nullif function.

Syntax

NULLIF( a, b )

In the syntax, replace each placeholder as follows:

a

The value to return when it does not equal b.

b

The value to compare with a.

Examples

The following SQL query calls NULLIF with two equal values and with two different values.

SELECT nullif(5, 5) AS equal_values, nullif(5, 3) AS different_values

The query returns the following result.

equal_values different_values

NULL

5

The following SQL query divides 100 by each value. Without NULLIF, the division by 0 returns an infinite value. With NULLIF, it returns NULL.

SELECT x, isinf(100 / x) AS plain_is_infinite, 100 / nullif(x, 0) AS with_nullif FROM (VALUES (1, 4), (2, 0)) AS t(id, x) ORDER BY id

The query returns the following results.

x plain_is_infinite with_nullif

4

false

25.0

0

true

NULL

The following SQL query turns a note that holds only spaces into NULL, by trimming it and comparing it with an empty string.

SELECT id, nullif(trim(note), '') AS note FROM (VALUES (1, 'shipped'), (2, ' '), (3, NULL) ) AS t(id, note) ORDER BY id

The query returns the following results.

id note

1

shipped

2

NULL

3

NULL

Lambda functions

A lambda function is an expression with named parameters, which another function calls for each element of a list. Write the lambda keyword, the parameter names separated by commas, a colon, and the expression that computes the result. For example, write lambda x: x + 1 or lambda x, y: x + y.

Pass a lambda function to a function that takes one. The list_transform function returns the result of the lambda function for each element. The list_filter function keeps the elements for which the result is true. The list_reduce function combines the elements into one value. Its lambda function takes the result so far and the next element. The lambda functions of list_transform and list_filter can take a second parameter, which holds the position of the element in the list, starting at 1.

The expression in a lambda function can use columns of the current row and call other functions.

To build a list from another list, you can also write a list comprehension. The list comprehension [expression FOR x IN list IF condition] returns expression for each element x of list for which condition is true. The IF part is optional.

Syntax

lambda parameter [, ...]: expression [ expression FOR x IN list [ IF condition ] ]

Examples

The following SQL query passes a lambda function with one parameter to list_transform, which multiplies each element by 10, and to list_filter, which keeps the even elements.

SELECT list_transform( [1, 2, 3], lambda x: x * 10 ) AS times_ten, list_filter( [1, 2, 3, 4], lambda x: x % 2 = 0 ) AS even_numbers

The query returns the following result.

times_ten even_numbers

[10, 20, 30]

[2, 4]

The following SQL query uses lambda functions with two parameters. list_reduce adds each element to the total so far, and list_transform multiplies each element by its position.

SELECT list_reduce( [1, 2, 3, 4], lambda total, x: total + x ) AS total, list_transform( [10, 20, 30], lambda x, i: x * i ) AS times_position

The query returns the following result.

total times_position

10

[10, 40, 90]

The following SQL query multiplies each element of the prices list by the rate column of the same row. This shows that a lambda function can read the columns of the current row.

SELECT id, list_transform(prices, lambda p: p * rate) AS scaled FROM (VALUES (1, [10, 20], 2), (2, [5], 3) ) AS t(id, prices, rate) ORDER BY id

The query returns the following results.

id scaled

1

[20, 40]

2

[15]

The following SQL query builds lists with list comprehensions, one with an IF condition and one without.

SELECT [ x * 10 FOR x IN [1, 2, 3, 4] IF x % 2 = 0 ] AS even_times_ten, [upper(s) FOR s IN ['a', 'b']] AS upper_letters

The query returns the following result.

even_times_ten upper_letters

[20, 40]

[A, B]

Considerations

Write lambda functions with the lambda keyword. DuckDB does not accept the arrow form, such as x -> x + 1, and the query fails.

Inside a lambda function, a parameter name hides a column with the same name. Choose parameter names that differ from the names of the columns that the expression uses.

In the list comprehension syntax, the outer square brackets are part of the SQL that you write.

Differences from Athena engine version 3

In Athena engine version 3, you write a lambda function with an arrow, as in transform(arr, x -> x + 1). In DuckDB, write the lambda keyword and use the DuckDB function name: list_transform(arr, lambda x: x + 1).

List literals, indexes, and slices

Write a list as values separated by commas in square brackets, such as [1, 2, 3]. ARRAY[1, 2, 3] and list_value(1, 2, 3) create the same list. The elements are converted to one common type, and the type of the list is that element type followed by [], such as INTEGER[]. A list can hold NULL elements and other lists.

To read one element, put its position in square brackets after the list, as in list[2]. Positions start at 1. A negative index counts from the end, so -1 is the last element. An index of 0, or one past either end of the list, returns NULL.

To read part of a list, put a start position (begin) and an end position (end) in the brackets, separated by a colon, as in list[2:4]. The result is a list that includes the elements at both positions. Leave out the start to begin at the first element, or the end to continue to the last. A third value is a step: list[1:5:2] returns every second element, and a negative step reads the list backward from the start position to the end position.

Indexes and slices also work on strings, where positions count characters. For example, 'database'[1:4] returns data. On a string, an index of 0 or an index past the end of the string returns an empty string, not NULL.

Syntax

[ value, ... ] list[index] list[begin:end] list[begin:end:step]

In the syntax, replace each placeholder as follows:

value

An element of the list. All elements must have types that can be converted to one common type.

list

The list to read from, or an expression that returns one, such as a column or a function call.

index

The position of the element to read, as an integer. 1 is the first element, and -1 is the last.

begin

The position of the first element of the slice. The default is the first element. This parameter is optional.

end

The position of the last element of the slice. The default is the last element. This parameter is optional.

step

The distance between the positions of the returned elements. The default is 1. This parameter is optional.

Examples

The following SQL query writes a list of integers, a list of strings with a NULL element, a list of lists, and a list written with the ARRAY keyword. It also returns the type of the list of integers.

SELECT [1, 2, 3] AS numbers, ['a', NULL, 'c'] AS letters, [[1, 2], [3]] AS nested, ARRAY[4, 5] AS array_keyword, typeof([1, 2, 3]) AS numbers_type

The query returns the following result.

numbers letters nested array_keyword numbers_type

[1, 2, 3]

[a, NULL, c]

[[1, 2], [3]]

[4, 5]

INTEGER[]

The following SQL query reads elements of a list column by position. Index 0 and an index past the end return NULL.

SELECT l[1] AS first_element, l[-1] AS last_element, l[0] AS index_zero, l[4] AS past_end FROM (VALUES ([10, 20, 30])) AS t(l)

The query returns the following result.

first_element last_element index_zero past_end

10

30

NULL

NULL

The following SQL query takes slices of a list. It returns a middle part, the first two elements, the elements from the fourth on, and the last two elements. It also returns every second element and the whole list in reverse order.

SELECT l[2:4] AS middle, l[:2] AS first_two, l[4:] AS from_fourth, l[-2:] AS last_two, l[1:5:2] AS every_other, l[5:1:-1] AS reversed FROM (VALUES ([10, 20, 30, 40, 50])) AS t(l)

The query returns the following result.

middle first_two from_fourth last_two every_other reversed

[20, 30, 40]

[10, 20]

[40, 50]

[40, 50]

[10, 30, 50]

[50, 40, 30, 20, 10]

The following SQL query reads the first character, the first four characters, and the last four characters of a string with an index and slices.

SELECT 'database'[1] AS first_character, 'database'[1:4] AS first_four, 'database'[-4:] AS last_four

The query returns the following result.

first_character first_four last_four

d

data

base

Considerations

In this syntax, the square brackets are part of the SQL that you write. You can leave out begin, end, or both, but keep the colon.

A list literal whose elements have no common type, such as [1, 'a'], makes the query fail.

A slice is limited to the positions that the list has, so it can return fewer elements than you ask for. When the start position comes after the end position and the step is positive, the result is an empty list.

To read an element of a list that a function returns, put the index after the call, as in string_split('a-b-c', '-')[2].

Differences from Athena engine version 3

In Athena engine version 3, arr[0] makes the query fail. In DuckDB, it returns NULL, because positions start at 1 and no element has position 0. If your query relies on the failure, check the index first. For more information about differences that change results, see Differences that change results without an error.

In Athena engine version 3, an array index past the end, such as ARRAY[10, 20, 30][5], makes the query fail. In DuckDB, it returns NULL. If your query relies on the failure, compare the index with len(arr) first.

In Athena engine version 3, you read an array element with element_at(arr, 2). In DuckDB, element_at accepts only a map, so write arr[2] or list_extract(arr, 2) instead.

Struct literals and field access

A struct holds a fixed set of named fields, and each field has its own type. Write a struct literal in curly braces, with each field name as a string, a colon, and the value, as in {'customer': 'alice', 'amount': 120.5}. You can also create the same struct with struct_pack(customer := 'alice', amount := 120.5). Its type is STRUCT(customer VARCHAR, amount DECIMAL(4,1)).

To read a field, write a dot and the field name after the struct, as in o.customer. You can also write the field name as a string in square brackets, as in o['customer']. Use the bracket form for a field name that contains spaces or other special characters. To read a field of a nested struct, or an element of a list in a struct, chain the parts, as in o.address.city or o.tags[1].

struct.* in the select list returns each field of the struct as its own column, named after the field.

row(value [, ...]) creates a struct whose fields have no names. Its type is TUPLE, such as TUPLE(VARCHAR, INTEGER), and query results show it in parentheses, as in (alice, 30). Read its fields by position, as in t[1], or cast it to a STRUCT type to name the fields.

Syntax

{ 'name': value [, ...] } struct.field struct['field'] struct.*

In the syntax, replace each placeholder as follows:

name

A field name, written as a string literal.

value

The value of the field. It can be of any type, including a list or another struct.

struct

The struct to read fields from, or an expression that returns one, such as a column.

field

The name of a field of struct.

Examples

The following SQL query writes a struct literal with two fields and returns its type.

SELECT { 'customer': 'alice', 'amount': 120.5 } AS order_info, typeof( {'customer': 'alice', 'amount': 120.5} ) AS order_type

The query returns the following result.

order_info order_type

{'customer': alice, 'amount': 120.5}

STRUCT(customer VARCHAR, amount DECIMAL(4,1))

The following SQL query reads the fields of a struct column with the dot form and the bracket form.

SELECT o.customer AS customer, o['amount'] AS amount FROM (VALUES ({'customer': 'bob', 'amount': 75.0}), ({'customer': 'alice', 'amount': 120.5}) ) AS t(o) ORDER BY customer

The query returns the following results.

customer amount

alice

120.5

bob

75.0

The following SQL query reads an element of a list inside a struct, a field of a struct inside a list, and a field of a nested struct.

SELECT ( {'id': 1, 'tags': ['new', 'gift']} ).tags[2] AS second_tag, [{'id': 1}, {'id': 2}][2].id AS second_id, ({'a': {'b': 42}}).a.b AS nested_field

The query returns the following result.

second_tag second_id nested_field

gift

2

42

The following SQL query uses o.* to return each field of a struct column as its own column.

SELECT o.* FROM (VALUES ({'customer': 'alice', 'amount': 120.5}) ) AS t(o)

The query returns the following result.

customer amount

alice

120.5

The following SQL query creates a struct without field names with row, reads its second field by position, and casts it to a STRUCT type to name its fields.

SELECT p AS person, typeof(p) AS person_type, p[2] AS second_field, CAST( p AS STRUCT(customer VARCHAR, age INTEGER) ) AS named_person FROM (SELECT row('alice', 30) AS p) AS t

The query returns the following result.

person person_type second_field named_person

(alice, 30)

TUPLE(VARCHAR, INTEGER)

30

{'customer': alice, 'age': 30}

Considerations

A field name that the struct does not have makes the query fail, in both the dot form and the bracket form.

When the name before a dot is both a table alias and a column name, a.b refers to column b of table a. To read a field of the struct column in that case, add the table alias, as in t.s.field, or use the bracket form.

In query results, a struct appears in curly braces with its field names in single quotation marks, and string values appear without quotation marks, as in {'customer': alice, 'amount': 120.5}.