Skip to content

Instantly share code, notes, and snippets.

@arshamalh
Last active December 23, 2021 08:15
Show Gist options
  • Save arshamalh/9252810d6f98abd381f9c06a3ed99d20 to your computer and use it in GitHub Desktop.
Save arshamalh/9252810d6f98abd381f9c06a3ed99d20 to your computer and use it in GitHub Desktop.
Postgres making arrays taking unique elements
-- Written by Arsham Arya
-- Any contribution makes readers happy.
INSERT INTO table_name (user_id, my_array_field)
VALUES (2233, array[112, 333])
ON CONFLICT (user_id) DO
UPDATE SET my_array_field = array(
SELECT DISTINCT unnest(table_name.my_array_field || array[112, 333])
) WHERE table_name.user_id = 2233;
/* Tips
sample user_id: 2233
sample array values: 112, 333
ON CONFLICT statment only works on postgres 9+ (IDK the exact version)
but you can use some techniques on older versions.
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment