Last active
October 15, 2023 17:40
-
-
Save Rowadz/072c867935f46622462a859d6e41ce19 to your computer and use it in GitHub Desktop.
How to use unnest and "with ordinality" to order rows or arrays based on their occurrence in a list
This file contains 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
create table emojies( | |
name text | |
); | |
INSERT INTO emojies VALUES('π»'), ('πΊ'), ('πΉ'), ('π€‘'), ('ποΈ'), ('πΈ') | |
select * from emojies | |
JOIN UNNEST(ARRAY['πΈ', 'π»', 'πΊ', 'ποΈ', 'πΉ', 'π€‘']) WITH ORDINALITY my_order_table("name", "ordinality_order") USING("name") | |
ORDER BY "ordinality_order" | |
create table test( | |
name text[], | |
id varchar(14), | |
email varchar(50) | |
); | |
INSERT INTO test (name, p_id, p_email) | |
VALUES (ARRAY['π±', 'πΏ'], 'random-id', '[email protected]'); | |
INSERT INTO test (p_name, p_id, p_email) | |
VALUES (ARRAY['π', 'π', 'π₯'], 'DELU-8529-HONA', '[email protected]'); | |
-- get the names from p_name array and order them by their occurrence order in the array | |
SELECT extracted_name | |
FROM test JOIN unnest(name::text[]) | |
WITH ORDINALITY my_table("extracted_name", "ordinality_order") on true | |
ORDER BY ordinality_order; | |
SELECT * FROM UNNEST(ARRAY['9c4e79d874d113a','1e3d0fpfdewa24']::TEXT[]) | |
WITH ORDINALITY my_table("id", "ordinality_order") | |
ORDER BY "ordinality_order"; | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment