I have some sql function that returns character varying
type. The output is something like this:
'TTFFFFNN'. I need to get this characters by index. How to convert character varying to array?
Asked
Active
Viewed 1,885 times
0

Erwin Brandstetter
- 605,456
- 145
- 1,078
- 1,228

Andrew
- 391
- 2
- 4
- 12
-
1`substring(some_column, index, 1)` – Dec 19 '14 at 16:38
2 Answers
1
Use string_to_array()
with NULL as delimiter (pg 9.1+):
SELECT string_to_array('TTFFFFNN'::text, NULL) AS arr;
In
string_to_array
, if the delimiter parameter is NULL, each character in the input string will become a separate element in the resulting array.
In older versions (pg 9.0-), the call with NULL returned NULL. (Fiddle.)
To get the 2nd position (example):
SELECT (string_to_array('TTFFFFNN'::text, NULL))[2] AS item2;
Alternatives
For single characters I would use substring()
directly, like @a_horse commented:
SELECT substring('TTFFFFNN'::text, 2, 1) AS item2;
SQL Fiddle showing both.
For strings with actual delimiters, I suggest split_part()
:
Only use regexp_split_to_array()
if you must. Regular expression processing is more expensive.

Community
- 1
- 1

Erwin Brandstetter
- 605,456
- 145
- 1,078
- 1,228
-
but indexing returns no result:select (string_to_array('TTFFFFNN'::text, NULL))[2] – Andrew Dec 19 '14 at 16:47
-
@Andrew: Sure it does. I tested, it works. Added example above. – Erwin Brandstetter Dec 19 '14 at 16:52
-
-
@Andrew: I suspect you are using an old version. I seem to remember different behavior with NULL in old versions. That's why you should *always* state the version of your software in the question ... – Erwin Brandstetter Dec 19 '14 at 16:58
-
the same question: do you know, why I can't call function in substing? select substing("FUNCGETRIGHTS"(0,89), 1, 1); My functions returns the same: 'TTFFFFNN'; Error tells that there is no fuction matches the given name and argument types and points at substring function; – Andrew Dec 19 '14 at 17:02
-
1
0
In addition to the solutions outlined by Erwin and a horse, you can use regexp_split_to_array()
with an empty regexp instead:
select regexp_split_to_array('TTFFFFNN'::text, '');
With an index, that becomes:
select (regexp_split_to_array('TTFFFFNN'::text, ''))[2];

Denis de Bernardy
- 75,850
- 13
- 131
- 154