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?
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.
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.
How about this:
SELECT (xpath('/my/xpath/expr', my_xml))[1] FROM my_table;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With