Skip to content

Instantly share code, notes, and snippets.

@Rowadz
Last active October 15, 2023 17:40
Show Gist options
  • Save Rowadz/072c867935f46622462a859d6e41ce19 to your computer and use it in GitHub Desktop.
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
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