1

In (postgres) SQL, this is valid syntax,

select (array[ [1,2,3], [4,5,6]])[1];

but not:

select array[ [1,2,3], [4,5,6]][1];

... which is a little surprising to me. What's going on here?

1
  • 1
    Strange, select array[ [1,2,3], [4,5,6]]::int[][1]; returns the full array. Which also seems like unpredictable behavior. Commented Jun 9, 2017 at 0:04

1 Answer 1

2

This is a parser issue. PostgreSQL uses Bison parser - additional parenthesis are required as protection against parsing collisions. The query processing is in stages: parsing, analyse, planning and execution. There are not enough information in parsing time to protect bison against possible collision and then some syntaxes are not disallowed.

Because a arrays was proprietary PostgreSQL feature (very successful) and syntax was not described by ANSI, a developers preferred some compromise design like good enough for users and doesn't require too complex code. A focus of PostgreSQL is in SQL and not in arrays processing. The Bison is very good mature tool, but sometimes due speed requirements some syntaxes are difficult or impossible.

select array[ [1,2,3], [4,5,6]]::int[][1]

There is not any magic if you know a fact, so limits in arrays types definition are syntactic sugar only. int[],int[1],int[] [100]is just int[]. Then array[ [1,2,3], [4,5,6]]::int[][1] is same like array[ [1,2,3], [4,5,6]]::int[] .. take a numeric array and cast it to integer array.

Sign up to request clarification or add additional context in comments.

2 Comments

"Because a arrays are proprietary PostgreSQL feature" that's not true. Arrays are defined by the SQL standard. And e.g. foo[1] or array[1,2,3,] are both valid standard SQL. The standard however does only defines one-dimensional arrays.
@a_horse_with_no_name - thank you for fix, I didn't know it. I though so only sets are supported without special syntax (I corrected the text).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.