1

In postgres, how can I query whether a columns contains int[][] (as opposed to int[]?)

I can query for information about the types of columns:

select *
from INFORMATION_SCHEMA.COLUMNS where table_name = 'mytable'

and I see udt_name and data_type jointly provide the base type of the columns. But none of these columns say what the arity of an array column is (arity would be 2 for int[][] and 1 for int[], and zero for int).

Postgres clearly has this information as I can see it if I view a table's schema in pgadmin3.

1 Answer 1

3

You can use array_ndims()

select 
    array_ndims(array[1,2]) as "int[]", 
    array_ndims(array[[1],[2]]) as "int[][]"

 int[] | int[][] 
-------+---------
     1 |       2
(1 row) 

The number of dimensions of an array column is stored in the system catalog pg_attribute, e.g.:

create table test(a int[], b int[][], c int[][][]);

select attname, typname, attndims
from pg_class c
join pg_attribute a on c.oid = attrelid
join pg_type t on t.oid = atttypid
where c.oid = 'test'::regclass
and attnum > 0;

 attname | typname | attndims 
---------+---------+----------
 a       | _int4   |        1
 b       | _int4   |        2
 c       | _int4   |        3
(3 rows)

The value of attndims reflects the way how the column was declared and may differ from dimensionality of actual values:

insert into test values (array[1], array[2], array[3]);

select array_ndims(a) as a, array_ndims(b) as b, array_ndims(c) as c
from test;

 a | b | c 
---+---+---
 1 | 1 | 1
(1 row)
Sign up to request clarification or add additional context in comments.

3 Comments

Maybe also worth mentioning that attndims is more like a documentation attribute. Presently, the number of dimensions of an array is not enforced, so any nonzero value effectively means "it's an array".
The value of attndims reflects the way how the column was declared in create table. I think the note in the documentation refers to the fact that in Postgres dimensionality is not forced regardless of how it was declared.
Yes, exactly. As I said (or at least, intended) values above 1 servers only documentation. Because actual column values' dimensions can differ from it.

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.