Last active
December 23, 2021 08:15
-
-
Save arshamalh/9252810d6f98abd381f9c06a3ed99d20 to your computer and use it in GitHub Desktop.
Postgres making arrays taking unique elements
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- 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