How Postgresql gets a specific value from an arrayed value.

Asked 2 years ago, Updated 2 years ago, 52 views

Environment: (PostgreSQL) 9.4.5

SELECT ARRAY ['foo', 'bar', 'hoge']AS fuga;

What should I do if I want to get only the middle bar from this array?

PHP-like

SELECT ARRAY ['foo', 'bar', 'hoge'][0]AS fuga;

If so,

ERROR: "[" or near it syntax error

I was scolded...

sql postgresql

2022-09-30 17:30

1 Answers

It is true that [x] can extract certain elements, but

  • Expressions representing an array must be enclosed in parentheses, unless they are simple column names, etc.
    Note: 4.2.3. subscript
  • The subscript starts with 1 (NULL if you specify an out-of-range subscript)
    Note: 8.15.3.Accessing an Array

Therefore, you can get bar by doing the following:

SELECT(ARRAY['foo', 'bar', 'hoge')[2]AS fuga;


2022-09-30 17:30

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.