34.16. columns

Представление columns содержит информацию обо всех колонках таблиц (или колонках представлений) в базе данных. Системные колонки (oid и т. д.) в нём не показываются. Оно содержит только те колонки, к которым имеет доступ текущий пользователь (являясь владельцем или имея некоторые права).

Таблица 34-14. Колонки columns

ИмяТип данныхОписание
table_catalogsql_identifierИмя базы данных, содержащей таблицу (всегда текущая база)
table_schemasql_identifierИмя схемы, содержащей таблицу
table_namesql_identifierИмя таблицы
column_namesql_identifierИмя колонки
ordinal_positioncardinal_numberПорядковый номер колонки в таблице (нумерация начинается с 1)
column_defaultcharacter_dataВыражение по умолчанию для колонки
is_nullableyes_or_noYES, если колонка может содержать NULL, или NO, если она не принимает NULL. Не будет принимать NULL колонка с ограничением не-NULL, но возможны и другие варианты.
data_typecharacter_dataТип данных колонки, если это встроенный тип, либо ARRAY, если это массив (в этом случае обратитесь к представлению element_types), иначе — USER-DEFINED (в этом случае тип определяется в udt_name и связанных колонках). Если колонка основана на домене, данная колонка показывает нижележащий тип домена (а сам домен показывается в domain_name и связанных колонках).
character_maximum_lengthcardinal_numberЕсли в data_type указан тип текстовой или битовой строки, это поле задаёт её объявленную максимальную длину; NULL для всех других типов данных, либо если максимальная длина не объявлена.
character_octet_lengthcardinal_numberЕсли в data_type указан тип символьной строки, это поле задаёт её максимально возможный размер в октетах (байтах); NULL для всех других типов данных. Максимальный размер в октетах зависит от объявленной максимальной длины в символах (см. выше) и от кодировки сервера.
numeric_precisioncardinal_numberЕсли в data_type указан числовой тип, эта колонка содержит точность (объявленную или неявную) типа для целевой колонки. Точность определяет число значащих цифр. Она может выражаться в десятичных (по основанию 10) или двоичных (по основанию 2) цифрах, согласно колонке numeric_precision_radix. Для всех других типов данных эта колонка содержит NULL.
numeric_precision_radixcardinal_numberЕсли в data_type указан числовой тип, в этой колонке определяется, по какому основанию задаются значения в колонках numeric_precision и numeric_scale. Возможные варианты: 2 или 10. Для всех других типов данных эта колонка содержит NULL.
numeric_scalecardinal_numberЕсли в data_type указан точный числовой тип, эта колонка содержит масштаб (объявленный или неявный) типа для целевой колонки. Масштаб определяет число значащих цифр справа от десятичной точки. Он может выражаться в десятичных (по основанию 10) или двоичных (по основанию 2) цифрах, согласно колонке numeric_precision_radix. Для всех других типов данных эта колонка содержит NULL.
datetime_precisioncardinal_numberЕсли в data_type указан тип даты, времени, отметки времени или интервала, эта колонка содержит точность (объявленную или неявную) в долях секунды типа для целевой колонки, то есть число десятичных цифр, сохраняемых после десятичной точки в значении секунд. Для всех других типов данных эта колонка содержит NULL.
interval_typecharacter_dataЕсли в data_type указан тип интервала, эта колонка определяет, какие поля принимает интервал в целевой колонке, например: YEAR TO MONTH, DAY TO SECOND и т. д. Если ограничения для полей не заданы (то есть, интервал принимает все поля), и для любых других типов данных это поле содержит NULL.
interval_precisioncardinal_numberОтносится к функциональности, отсутствующей в PostgreSQL (см. поле datetime_precision, определяющее точность в долях секунды для типов интервалов)
character_set_catalogsql_identifierОтносится к функциональности, отсутствующей в PostgreSQL
character_set_schemasql_identifierОтносится к функциональности, отсутствующей в PostgreSQL
character_set_namesql_identifierОтносится к функциональности, отсутствующей в PostgreSQL
collation_catalogsql_identifierИмя базы данных, содержащей правило сортировки колонки (это всегда текущая база), либо NULL, если это правило по умолчанию или тип данных колонки несортируемый
collation_schemasql_identifierИмя схемы, содержащей правило сортировки колонки, либо NULL, если это правило по умолчанию или тип данных колонки несортируемый
collation_namesql_identifierИмя правила сортировки колонки, либо NULL, если это правило по умолчанию или тип данных колонки несортируемый
domain_catalogsql_identifierЕсли целевая колонка имеет тип домена, эта колонка содержит имя базы данных, в которой определён домен (всегда текущая база), иначе NULL.
domain_schemasql_identifierЕсли целевая колонка имеет тип домена, эта колонка содержит имя схемы, в которой определён домен, иначе NULL.
domain_namesql_identifierЕсли целевая колонка имеет тип домена, эта колонка содержит имя домена, иначе NULL.
udt_catalogsql_identifierИмя базы данных, в которой определён тип (если применимо, нижележащий тип домена) колонки (всегда текущая база)
udt_schemasql_identifierИмя схемы, в которой определён тип (если применимо, нижележащий тип домена) колонки (всегда текущая база)
udt_namesql_identifierИмя типа данных колонки (если применимо, нижележащий тип домена)
scope_catalogsql_identifierОтносится к функциональности, отсутствующей в PostgreSQL
scope_schemasql_identifierОтносится к функциональности, отсутствующей в PostgreSQL
scope_namesql_identifierОтносится к функциональности, отсутствующей в PostgreSQL
maximum_cardinalitycardinal_numberВсегда NULL, так как массивы имеют неограниченную максимальную ёмкость в PostgreSQL
dtd_identifiersql_identifierИдентификатор дескриптора типа данных колонки, уникальный среди всех дескрипторов типов, относящихся к таблице. Он в основном полезен для соединения с другими экземплярами таких идентификаторов. (Конкретный формат идентификатора не определён и не гарантируется, что он останется неизменным в будущих версиях.)
is_self_referencingyes_or_noОтносится к функциональности, отсутствующей в PostgreSQL
is_identityyes_or_noОтносится к функциональности, отсутствующей в PostgreSQL
identity_generationcharacter_dataОтносится к функциональности, отсутствующей в PostgreSQL
identity_startcharacter_dataОтносится к функциональности, отсутствующей в PostgreSQL
identity_incrementcharacter_dataОтносится к функциональности, отсутствующей в PostgreSQL
identity_maximumcharacter_dataОтносится к функциональности, отсутствующей в PostgreSQL
identity_minimumcharacter_dataОтносится к функциональности, отсутствующей в PostgreSQL
identity_cycleyes_or_noОтносится к функциональности, отсутствующей в PostgreSQL
is_generatedcharacter_dataОтносится к функциональности, отсутствующей в PostgreSQL
generation_expressioncharacter_dataОтносится к функциональности, отсутствующей в PostgreSQL
is_updatableyes_or_noYES, если колонка допускает изменение, или NO в противном случае (колонки в базовых таблицах всегда изменяемые, но в представлениях — не обязательно)

Так как типы данных могут определяться в SQL множеством способом и PostgreSQL добавляет дополнительные варианты, представление типов в информационной схеме может быть довольно сложным. Колонка data_type предназначена для идентификации нижележащего встроенного типа колонки. В PostgreSQL это означает, что данный тип определён в схеме системного каталога pg_catalog. Эта колонка может быть полезной, если приложение способно особым образом воспринимать встроенные типы (например, форматировать числовые типы по-другому или задействовать данные в колонках точности). Колонки udt_name, udt_schema и udt_catalog всегда указывают на нижележащий тип данных колонки, даже если колонка основана на домене. (Так как в PostgreSQL встроенные типы не отличаются от определённых пользователем, в этом представлении выводятся и они. Это расширение стандарта SQL.) Эти колонки должны учитываться, когда приложению нужно обрабатывать данные в зависимости от типа, так как в этом случае не важно, основана ли колонка на домене. Если колонка основана на домене, на него указывают колонки domain_name, domain_schema и domain_catalog. Если вы хотите связать колонки с их типами данных и обработать домены как отдельные типы, вы можете записать coalesce(domain_name, udt_name) и т. п.

34.16. columns

The view columns contains information about all table columns (or view columns) in the database. System columns (oid, etc.) are not included. Only those columns are shown that the current user has access to (by way of being the owner or having some privilege).

Table 34-14. columns Columns

NameData TypeDescription
table_catalogsql_identifierName of the database containing the table (always the current database)
table_schemasql_identifierName of the schema containing the table
table_namesql_identifierName of the table
column_namesql_identifierName of the column
ordinal_positioncardinal_numberOrdinal position of the column within the table (count starts at 1)
column_defaultcharacter_dataDefault expression of the column
is_nullableyes_or_noYES if the column is possibly nullable, NO if it is known not nullable. A not-null constraint is one way a column can be known not nullable, but there can be others.
data_typecharacter_data Data type of the column, if it is a built-in type, or ARRAY if it is some array (in that case, see the view element_types), else USER-DEFINED (in that case, the type is identified in udt_name and associated columns). If the column is based on a domain, this column refers to the type underlying the domain (and the domain is identified in domain_name and associated columns).
character_maximum_lengthcardinal_number If data_type identifies a character or bit string type, the declared maximum length; null for all other data types or if no maximum length was declared.
character_octet_lengthcardinal_number If data_type identifies a character type, the maximum possible length in octets (bytes) of a datum; null for all other data types. The maximum octet length depends on the declared character maximum length (see above) and the server encoding.
numeric_precisioncardinal_number If data_type identifies a numeric type, this column contains the (declared or implicit) precision of the type for this column. The precision indicates the number of significant digits. It can be expressed in decimal (base 10) or binary (base 2) terms, as specified in the column numeric_precision_radix. For all other data types, this column is null.
numeric_precision_radixcardinal_number If data_type identifies a numeric type, this column indicates in which base the values in the columns numeric_precision and numeric_scale are expressed. The value is either 2 or 10. For all other data types, this column is null.
numeric_scalecardinal_number If data_type identifies an exact numeric type, this column contains the (declared or implicit) scale of the type for this column. The scale indicates the number of significant digits to the right of the decimal point. It can be expressed in decimal (base 10) or binary (base 2) terms, as specified in the column numeric_precision_radix. For all other data types, this column is null.
datetime_precisioncardinal_number If data_type identifies a date, time, timestamp, or interval type, this column contains the (declared or implicit) fractional seconds precision of the type for this column, that is, the number of decimal digits maintained following the decimal point in the seconds value. For all other data types, this column is null.
interval_typecharacter_data If data_type identifies an interval type, this column contains the specification which fields the intervals include for this column, e.g., YEAR TO MONTH, DAY TO SECOND, etc. If no field restrictions were specified (that is, the interval accepts all fields), and for all other data types, this field is null.
interval_precisioncardinal_number Applies to a feature not available in PostgreSQL (see datetime_precision for the fractional seconds precision of interval type columns)
character_set_catalogsql_identifierApplies to a feature not available in PostgreSQL
character_set_schemasql_identifierApplies to a feature not available in PostgreSQL
character_set_namesql_identifierApplies to a feature not available in PostgreSQL
collation_catalogsql_identifier Name of the database containing the collation of the column (always the current database), null if default or the data type of the column is not collatable
collation_schemasql_identifier Name of the schema containing the collation of the column, null if default or the data type of the column is not collatable
collation_namesql_identifier Name of the collation of the column, null if default or the data type of the column is not collatable
domain_catalogsql_identifier If the column has a domain type, the name of the database that the domain is defined in (always the current database), else null.
domain_schemasql_identifier If the column has a domain type, the name of the schema that the domain is defined in, else null.
domain_namesql_identifierIf the column has a domain type, the name of the domain, else null.
udt_catalogsql_identifier Name of the database that the column data type (the underlying type of the domain, if applicable) is defined in (always the current database)
udt_schemasql_identifier Name of the schema that the column data type (the underlying type of the domain, if applicable) is defined in
udt_namesql_identifier Name of the column data type (the underlying type of the domain, if applicable)
scope_catalogsql_identifierApplies to a feature not available in PostgreSQL
scope_schemasql_identifierApplies to a feature not available in PostgreSQL
scope_namesql_identifierApplies to a feature not available in PostgreSQL
maximum_cardinalitycardinal_numberAlways null, because arrays always have unlimited maximum cardinality in PostgreSQL
dtd_identifiersql_identifier An identifier of the data type descriptor of the column, unique among the data type descriptors pertaining to the table. This is mainly useful for joining with other instances of such identifiers. (The specific format of the identifier is not defined and not guaranteed to remain the same in future versions.)
is_self_referencingyes_or_noApplies to a feature not available in PostgreSQL
is_identityyes_or_noApplies to a feature not available in PostgreSQL
identity_generationcharacter_dataApplies to a feature not available in PostgreSQL
identity_startcharacter_dataApplies to a feature not available in PostgreSQL
identity_incrementcharacter_dataApplies to a feature not available in PostgreSQL
identity_maximumcharacter_dataApplies to a feature not available in PostgreSQL
identity_minimumcharacter_dataApplies to a feature not available in PostgreSQL
identity_cycleyes_or_noApplies to a feature not available in PostgreSQL
is_generatedcharacter_dataApplies to a feature not available in PostgreSQL
generation_expressioncharacter_dataApplies to a feature not available in PostgreSQL
is_updatableyes_or_noYES if the column is updatable, NO if not (Columns in base tables are always updatable, columns in views not necessarily)

Since data types can be defined in a variety of ways in SQL, and PostgreSQL contains additional ways to define data types, their representation in the information schema can be somewhat difficult. The column data_type is supposed to identify the underlying built-in type of the column. In PostgreSQL, this means that the type is defined in the system catalog schema pg_catalog. This column might be useful if the application can handle the well-known built-in types specially (for example, format the numeric types differently or use the data in the precision columns). The columns udt_name, udt_schema, and udt_catalog always identify the underlying data type of the column, even if the column is based on a domain. (Since PostgreSQL treats built-in types like user-defined types, built-in types appear here as well. This is an extension of the SQL standard.) These columns should be used if an application wants to process data differently according to the type, because in that case it wouldn't matter if the column is really based on a domain. If the column is based on a domain, the identity of the domain is stored in the columns domain_name, domain_schema, and domain_catalog. If you want to pair up columns with their associated data types and treat domains as separate types, you could write coalesce(domain_name, udt_name), etc.

FAQ