trim_array Drops Elements From The End
Shrink arrays from the tail with trim_array, which trims only the first dimension of multidimensional input and returns an empty array when n reaches length.
Code
-- trim_array(数组, n):去掉末尾 n 个元素
SELECT trim_array(ARRAY[1, 2, 3, 4, 5, 6], 2) AS dropped_two;
-- n 等于长度时得到空数组(不报错)
SELECT trim_array(ARRAY['a', 'b'], 2) AS emptied;
-- 只作用于第一维:多维数组按外层行裁剪,行内元素原样保留
SELECT trim_array(ARRAY[[1, 2], [3, 4], [5, 6]], 1) AS rows_trimmed;
-- 与 array_remove(按值删除所有匹配)互补:裁数量 vs 删内容
SELECT trim_array(ARRAY[7, 8, 9], 1) AS by_count,
array_remove(ARRAY[7, 8, 9, 7], 7) AS by_value;
-- 裁剪后的下标仍从 1 起算,与原数组无关
SELECT (trim_array(ARRAY[10, 20, 30], 1))[1] AS first_after_trim;How it works
Every statement operates on an array literal, so the file needs no table and no setup.
trim_array(values, n) shortens the array by dropping its last n elements. The remaining elements keep their order and the result is re-indexed from 1, so the first element of a trimmed array is trim_array(...)[1] regardless of what was removed.
Multi-dimensional behaviour
Only the first dimension is trimmed. trim_array(ARRAY[[1, 2], [3, 4], [5, 6]], 1) therefore removes one whole row and leaves each remaining row intact.
Key statements
SELECT trim_array(ARRAY[1, 2, 3, 4, 5, 6], 2) AS dropped_two;
SELECT (trim_array(ARRAY[10, 20, 30], 1))[1] AS first_after_trim;
Interactive Tools for This Topic
PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.SQL DDL to TypeScript ConverterConvert SQL CREATE TABLE DDL statements into strict TypeScript interfaces with nullable, array, enum, JSONB, and Date or ISO string column mappings.Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.Levenshtein Distance CalculatorCompute the classic edit distance between two strings with a space-optimized DP and a normalized similarity percentage.
Report a problem with this exampleOpens a pre-filled issue on GitHub.