Returns a subset of an array, starting at a given index for a specified number of elements.
Syntax
HELPCODEESCAPE-plaintext
array<T> slice(array<T> <a>, <start>, <length>)Parameters
| Parameter | Required | Description |
|---|---|---|
a | Yes | The input array. T can be any data type. |
start | Yes | The index at which to start the slice. The minimum positive value is 1. Negative values count from the end of the array, but elements are always returned left to right. |
length | Yes | The number of elements to return. Must be 0 or greater. If length exceeds the number of elements remaining after start, the function returns all elements from start to the end of the array. |
Usage notes
Indexing is 1-based:
start = 1refers to the first element.A negative
startcounts from the end of the array. For example,start = -2refers to the second-to-last element. Elements are still returned left to right.Setting
length = 0returns an empty array.If
lengthexceeds the number of elements remaining afterstart, the function returns all remaining elements rather than raising an error.
Return value
Returns an ARRAY of the same element type T as the input array.
Examples
All examples use the array array(10, 20, 20, null, null, 30).
HELPCODEESCAPE-plaintext
-- Start at index 1, return 3 elements.
SELECT slice(array(10, 20, 20, null, null, 30), 1, 3);
-- [10, 20, 20]
-- Start at index -2 (second-to-last element), return 2 elements.
SELECT slice(array(10, 20, 20, null, null, 30), -2, 2);
-- [null, 30]
-- Start at index 3, request 10 elements (only 4 remain): returns all remaining.
SELECT slice(array(10, 20, 20, null, null, 30), 3, 10);
-- [20, null, null, 30]
-- Start at index 3, return 0 elements.
SELECT slice(array(10, 20, 20, null, null, 30), 3, 0);
-- []Related functions
SLICE is a complex type function. For more information about functions for processing ARRAY, MAP, STRUCT, and JSON data, see Complex type functions.