Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can PostgreSQL select from an array returned by a function?

This query fails:

SELECT xpath('/my/xpath/expr', my_xml)[1] FROM my_table

ERROR:  syntax error at or near "["

But this one works:

SELECT x[1] FROM
    (SELECT xpath('/my/xpath/expr', my_xml) as x FROM my_table) as ss

My xpath expression always returns only a single value, but the Postgres xpath function returns an array. I want to select the first value in the array. While the subselect works, it's pretty ugly.

Why doesn't the first query work, and is there a cleaner way to do this than the second query?

like image 617
DNS Avatar asked Apr 17 '09 18:04

DNS


People also ask

How do I select an array in PostgreSQL?

PostgreSQL allows us to define a table column as an array type. The array must be of a valid data type such as integer, character, or user-defined types. To insert values into an array column, we use the ARRAY constructor.

How do I return a selected query in PostgreSQL?

To return a table from the function, you use RETURNS TABLE syntax and specify the columns of the table. Each column is separated by a comma (, ). In the function, we return a query that is a result of a SELECT statement.


1 Answers

How about this:

SELECT (xpath('/my/xpath/expr', my_xml))[1] FROM my_table;
like image 195
Milen A. Radev Avatar answered Sep 21 '22 03:09

Milen A. Radev