array_remove And array_replace Edit Lists
array_remove deletes every element equal to the target and array_replace swaps each match; missing targets return the array untouched instead of erroring.
Code
WITH orders AS (
SELECT * FROM (VALUES
(1, ARRAY['gift', 'rush', 'legacy']),
(2, ARRAY['rush', 'rush', 'bulk'])
) AS t(order_id, tag_list)
)
SELECT
order_id,
-- drop every element equal to the target
array_remove(tag_list, 'legacy') AS cleaned,
-- swap every match for the new value
array_replace(tag_list, 'rush', 'priority') AS renamed,
-- an absent target returns the array untouched, no error
array_remove(tag_list, 'absent') AS untouched
FROM orders
ORDER BY order_id;What the demo edits
Two orders carry tag lists. array_remove(tag_list, ‘legacy’) deletes every equal element, so order 1 loses its legacy tag while order 2 keeps its rush pair; array_replace(tag_list, ‘rush’, ‘priority’) swaps every match, turning the two rush tags of order 2 into priority entries.
The absent-target probe closes it: array_remove(tag_list, ‘absent’) prints the original array unchanged, with no error and no empty array, which is what makes these functions safe to run on unverified data.
Points to remember
- Both functions process all matches, not just the first.
- Types must line up: the target is compared as the array element type.
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.
FAQ
- What happens when the target value is missing?
- Both array_remove and array_replace return the input array unchanged; the untouched column in the demo prints the original tag list for the absent target.
Report a problem with this exampleOpens a pre-filled issue on GitHub.