Home > Database > Mysql Tutorial > How to Get Element Numbers with PostgreSQL's unnest() Function?

How to Get Element Numbers with PostgreSQL's unnest() Function?

Mary-Kate Olsen
Release: 2025-01-23 04:19:11
Original
620 people have browsed it

How to Get Element Numbers with PostgreSQL's unnest() Function?

Use PostgreSQL’s unnest() function to get the element number

The unnest() function is useful when working with columns containing delimited values. However, getting the element value and its number simultaneously can be a challenge.

PostgreSQL 14 or higher

For comma separated strings, using the string_to_table() function provides a simple solution:

SELECT t.id, a.elem, a.nr
FROM tbl t
LEFT JOIN LATERAL string_to_table(t.elements, ',') WITH ORDINALITY AS a(elem, nr) ON true;
Copy after login

PostgreSQL 9.4 or higher

With ORDINALITY added in PostgreSQL 9.4 to functions that return collections, you can use the following query:

SELECT t.id, a.elem, a.nr
FROM tbl AS t
LEFT JOIN LATERAL unnest(string_to_array(t.elements, ',')) WITH ORDINALITY AS a(elem, nr) ON true;
Copy after login

PostgreSQL 8.4 - 9.3

To ensure the sequence number of elements in a string:

SELECT id, arr[nr] AS elem, nr
FROM (
   SELECT *, generate_subscripts(arr, 1) AS nr
   FROM (SELECT id, string_to_array(elements, ' ') AS arr FROM tbl) t
   ) sub;
Copy after login

PostgreSQL 8.1 - 8.4

For versions of PostgreSQL prior to 8.4, you can create a function to achieve the desired result:

CREATE FUNCTION f_unnest_ord(anyarray, OUT val anyelement, OUT ordinality integer)
  RETURNS SETOF record
  LANGUAGE sql IMMUTABLE AS
'SELECT [i], i - array_lower(,1) + 1
 FROM   generate_series(array_lower(,1), array_upper(,1)) i';
Copy after login

The above is the detailed content of How to Get Element Numbers with PostgreSQL's unnest() Function?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template