Return a random sample of n elements from an array without replacement.
ARRAY_SAMPLE(array, n)
## Overview Returns an array of n elements drawn uniformly at random without replacement from the input array. ARRAY_SAMPLE is the inline analogue of a row-level TABLESAMPLE and is useful for producing deterministic-sized random subsets of per-row collections, such as a small audit sample of events or tags. Typical uses include drawing a small random subset for QA or profiling, producing a bounded-size preview of a potentially large per-row array, and feeding stochastic algorithms that require a random prefix of a collection. ## Behavior - Returns an ARRAY<T> of length n containing distinct elements selected from the input (elements are sampled without replacement). - Selection is uniform over positions, not over distinct values. Duplicate elements in the input can appear in the sample. - Order of elements in the result is non-deterministic. - Sampling is done per row. Two calls on the same row can produce different results unless a session-level random seed is fixed. - n must be less than or equal to the input length; a larger n raises an error. - Does not mutate the input. ## Null and empty handling - NULL input array returns NULL. - Empty input array with n = 0 returns an empty array; any positive n raises an error. - NULL elements in the input are valid candidates and may appear in the sample. - n = 0 always returns an empty array. ## Compatibility - Matches the array/map SQL convention for ARRAY_SAMPLE without a fixed seed. Where a reproducible sample is required, combine ARRAY_SHUFFLE with a deterministic seed plus SLICE(result, 1, n).
| Name | Type | Description |
|---|---|---|
array | Specifies the input array from which elements are sampled. | |
n | Specifies the sample size. Must be a non-negative integer not exceeding the array length. Zero produces an empty array. |
-- Sample two elements
SELECT ARRAY_SAMPLE(ARRAY[1, 2, 3, 4, 5], 2); -- e.g. [3, 1]
-- Sample exactly one element
SELECT ARRAY_SAMPLE(ARRAY['a', 'b', 'c'], 1); -- e.g. ['b']
-- Sample all elements (equivalent to a shuffle)
SELECT ARRAY_SAMPLE(ARRAY[10, 20, 30], 3); -- e.g. [20, 30, 10]
-- Zero sample size yields an empty array
SELECT ARRAY_SAMPLE(ARRAY[1, 2, 3], 0); -- []
-- Draw a random subset of per-session events for QA inspection
SELECT session_id, ARRAY_SAMPLE(events, 3) AS sample_events
FROM analytics.events.user_sessions;
-- NULL input array returns NULL
SELECT ARRAY_SAMPLE(CAST(NULL AS ARRAY<INT>), 2); -- NULL