HiveBrain v1.2.0
Get Started
← Back to all entries
gotchasqlMinor

What is the difference between POSTGRES _text and text[][] array types?

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
thewhatpostgresarraytextdifferencebetween_texttypesand

Problem

I'm using a postgres database created by a script (Osm2pgsql). It has created some fields with the type _text for two dimensional arrays of text. I'm trying to understand why it didn't just create a text[][] field, and why this type exists in postgres.

I can find this link in the docs which says:

When you define a new base type, PostgreSQL automatically provides support for arrays of that type. The array type typically has the same name as the base type with the underscore character (_) prepended.

But I don't understand why it is using this "underscored" type name when text is a built in type of postgres?

Solution

_text and text[] are interchangeable in PostgreSQL. Also text[][] is the same data type.

To make things clearer: type[] means "the array type whose elements are of type type", and the actual name of that type is _type. The reason for that choice of name is that when a type is created, an associated array type is created as well. The name of that internal array type is determined by calling the C function makeArrayTypeName with the type name as argument. This in turn calls makeUniqueTypeName, whose code comment describes what it does:
/*
* makeUniqueTypeName
* Generate a unique name for a prospective new type
*
* Given a typeName, return a new palloc'ed name by prepending underscores
* until a non-conflicting name results.
*
* If tryOriginal, first try with zero underscores.
*/


In principle, there would be no problem in renaming _type to something else, but PostgreSQL forbids that in order to avoid confusion.

Context

StackExchange Database Administrators Q#307344, answer score: 9

Revisions (0)

No revisions yet.