CREATE_TYPE(7pg18)
๐ NAME ๐
okay so bestie, welcome to CREATE_TYPE โ that's the CREATE TYPE(7) page from the PostgreSQL 18.6 Documentation, and it's literally the whole entire guide to define a new data type. no cap. ๐ซถ
โจ SYNOPSIS โจ
CREATE TYPE name AS
( [ attribute_name data_type [ COLLATE collation ] [, ... ] ] )
CREATE TYPE name AS ENUM
( [ 'label' [, ... ] ] )
CREATE TYPE name AS RANGE (
SUBTYPE = subtype
[ , SUBTYPE_OPCLASS = subtype_operator_class ]
[ , COLLATION = collation ]
[ , CANONICAL = canonical_function ]
[ , SUBTYPE_DIFF = subtype_diff_function ]
[ , MULTIRANGE_TYPE_NAME = multirange_type_name ]
)
CREATE TYPE name (
INPUT = input_function,
OUTPUT = output_function
[ , RECEIVE = receive_function ]
[ , SEND = send_function ]
[ , TYPMOD_IN = type_modifier_input_function ]
[ , TYPMOD_OUT = type_modifier_output_function ]
[ , ANALYZE = analyze_function ]
[ , SUBSCRIPT = subscript_function ]
[ , INTERNALLENGTH = { internallength | VARIABLE } ]
[ , PASSEDBYVALUE ]
[ , ALIGNMENT = alignment ]
[ , STORAGE = storage ]
[ , LIKE = like_type ]
[ , CATEGORY = category ]
[ , PREFERRED = preferred ]
[ , DEFAULT = default ]
[ , ELEMENT = element ]
[ , DELIMITER = delimiter ]
[ , COLLATABLE = collatable ]
)
CREATE TYPE name
๐ฆ DESCRIPTION ๐ฆ
CREATE TYPE registers a brand-new data type so it can be used in the current database. and the glow-up? the user who defines a type becomes its owner. main character energy, honestly. ๐
if you hand over a schema name, the type gets created in that schema. if you don't, it lands in the current schema. the type name has to be distinct from the name of any existing type or domain in the same schema. and lowkey there's a plot twist here: because tables have associated data types, the type name must also be distinct from the name of any existing table in the same schema. so no sneaky name collisions, periodt.
there are five forms of CREATE TYPE, exactly as shown in the syntax synopsis above. they respectively create a composite type, an enum type, a range type, a base type, or a shell type. the first four are discussed one by one below. and a shell type? it's just a placeholder for a type you're gonna define later โ you create it by issuing CREATE TYPE with no parameters except for the type name. shell types are needed as forward references when you're creating range types and base types, as discussed in those sections. iykyk. ๐
๐ Composite Types ๐
the first form of CREATE TYPE creates a composite type. you specify it with a list of attribute names and data types. an attribute's collation can be specified too, if its data type is collatable. a composite type is basically the same thing as the row type of a table, except using CREATE TYPE means you don't have to create an actual table when all you wanted was to define a type. a stand-alone composite type is useful, for example, as the argument or return type of a function. so useful. so iconic. โจ
to be able to create a composite type, you must have USAGE privilege on all attribute types. no privilege, no type. ๐
๐ธ Enumerated Types ๐ธ
the second form of CREATE TYPE creates an enumerated (enum) type, as described in Section 8.7. enum types take a list of quoted labels, and every single one of them must be less than NAMEDATALEN bytes long (64 bytes in a standard PostgreSQL build). and yes, it is possible to create an enumerated type with zero labels โ but bestie, such a type cannot be used to hold values until at least one label is added using ALTER TYPE. so it's giving "decorative until you commit". ๐
๐ Range Types ๐
the third form of CREATE TYPE creates a new range type, as described in Section 8.17.
the range type's subtype can be any type with an associated b-tree operator class (that's what determines the ordering of values for the range type). normally the subtype's default b-tree operator class handles the ordering; to use a non-default operator class, specify its name with subtype_opclass. and if the subtype is collatable, and you want a non-default collation in the range's ordering, specify the collation you want with the collation option. ๐
the optional canonical function must take one argument of the range type being defined, and return a value of the same type. this gets used to convert range values to a canonical form, when applicable. see Section 8.17.8 for more info. ngl creating a canonical function is a bit tricky, because it has to be defined before the range type can be declared. the way around it: you first create a shell type, which is a placeholder type with no properties except a name and an owner. you do that by issuing the command CREATE TYPE name, with no additional parameters. then the function can be declared using the shell type as argument and result, and finally the range type can be declared using the same name. this automatically replaces the shell type entry with a valid range type. it's giving glow-up arc. ๐ฆ
the optional subtype_diff function must take two values of the subtype type as argument, and return a double precision value representing the difference between the two given values. while it's optional, providing it allows much greater efficiency of GiST indexes on columns of the range type. see Section 8.17.8 for more information. ๐ฅ
the optional multirange_type_name parameter specifies the name of the corresponding multirange type. if you don't specify it, the name is chosen automatically like this:
- if the range type name contains the substring
range, then the multirange type name is formed by replacement of therangesubstring withmultirangein the range type name. - otherwise, the multirange type name is formed by appending a
_multirangesuffix to the range type name.
to be able to create a range type, you must have USAGE privilege on the subtype. ๐ซถ
๐ฅ Base Types ๐ฅ
the fourth form of CREATE TYPE creates a new base type (scalar type). and here's the thing โ to create a new base type, you must be a superuser. why? because this restriction is made because an erroneous type definition could confuse or even crash the server. ๐ so yeah, respect the gatekeeping.
the parameters can appear in any order, not only the order illustrated above, and most of them are optional. you must register two or more functions (using CREATE FUNCTION) before defining the type. the support functions input_function and output_function are required, while the functions receive_function, send_function, type_modifier_input_function, type_modifier_output_function, analyze_function, and subscript_function are optional. generally these functions have to be coded in C or another low-level language. okay so let's go through them.
the input_function converts the type's external textual representation to the internal representation used by the operators and functions defined for the type. output_function performs the reverse transformation. the input function can be declared as taking one argument of type cstring, or as taking three arguments of types cstring, oid, integer. here's the breakdown:
- the first argument is the input text as a C string,
- the second argument is the type's own OID (except for array types, which instead receive their element type's OID),
- and the third is the typmod of the destination column, if known (
-1will be passed if not).
the input function must return a value of the data type itself. usually, an input function should be declared STRICT; if it's not, it will be called with a NULL first parameter when reading a NULL input value. the function must still return NULL in this case, unless it raises an error. (this case is mainly meant to support domain input functions, which might need to reject NULL inputs.) the output function must be declared as taking one argument of the new data type. the output function must return type cstring. output functions are not invoked for NULL values.
the optional receive_function converts the type's external binary representation to the internal representation. if this function is not supplied, the type cannot participate in binary input. the binary representation should be chosen to be cheap to convert to internal form, while being reasonably portable. (for example, the standard integer data types use network byte order as the external binary representation, while the internal representation is in the machine's native byte order.) the receive function should perform adequate checking to ensure that the value is valid. the receive function can be declared as taking one argument of type internal, or as taking three arguments of types internal, oid, integer. the first argument is a pointer to a StringInfo buffer holding the received byte string; the optional arguments are the same as for the text input function. the receive function must return a value of the data type itself. usually, a receive function should be declared STRICT; if it's not, it will be called with a NULL first parameter when reading a NULL input value. the function must still return NULL in this case, unless it raises an error. (this case is mainly meant to support domain receive functions, which might need to reject NULL inputs.) similarly, the optional send_function converts from the internal representation to the external binary representation. if this function is not supplied, the type cannot participate in binary output. the send function must be declared as taking one argument of the new data type. the send function must return type bytea. send functions are not invoked for NULL values. ๐
and at this point you should be wondering: how can the input and output functions be declared to have results or arguments of the new type, when they have to be created before the new type can be created?? the answer, bestie, is that the type should first be defined as a shell type โ a placeholder type that has no properties except a name and an owner. this is done by issuing the command CREATE TYPE name, with no additional parameters. then the C I/O functions can be defined referencing the shell type. finally, CREATE TYPE with a full definition replaces the shell entry with a complete, valid type definition, after which the new type can be used normally. chicken-and-egg problem? solved. ate. ๐
okay so the optional type_modifier_input_function and type_modifier_output_function are needed when your type supports modifiers โ aka those optional constraints you can staple onto a type declaration, like char(5) or numeric(30,2). PostgreSQL lets user-defined types take one or more simple constants or identifiers as modifiers. But bestie, hear me out: that info has to be packable into a single non-negative integer so it can live in the system catalogs. ๐พ
So the type_modifier_input_function gets handed the declared modifier(s) as a cstring array. It must check those values for validity (throw an error if they're wrong, no hesitation ๐), and if they're correct, return a single non-negative integer that gets stored as the column "typmod". And listen โ type modifiers get rejected if the type doesn't have a type_modifier_input_function. Periodt.
Then the type_modifier_output_function does the reverse glow-up: it converts that internal integer typmod value back into the correct form for user display. It must return a cstring value that is the exact string to append to the type name โ for example, numeric's function might return (30,2). It's totally allowed to omit the type_modifier_output_function, and if you do, the default display format is just the stored typmod integer value wrapped in parentheses. simple as that โจ
The optional analyze_function does type-specific statistics collection for columns of the data type. By default, ANALYZE will try to gather stats using the type's "equals" and "less-than" operators โ but only if there's a default b-tree operator class for the type. For non-scalar types this behavior is likely to be unsuitable, so you can override it by specifying a custom analysis function. The analysis function must be declared to take a single argument of type internal, and return a boolean result. The detailed API for analysis functions lives in src/include/commands/vacuum.h. ๐
The optional subscript_function lets your data type be subscripted in SQL commands. Quick clarification tho: specifying this function does not make the type a "true" array type โ for example, it won't be a candidate for the result type of ARRAY[] constructs. But if subscripting a value of the type is just a natural notation for extracting data from it, then a subscript_function can be written to define what that means. The subscript function must be declared to take a single argument of type internal, and return an internal result, which is a pointer to a struct of methods (functions) that implement subscripting. The detailed API for subscript functions appears in src/include/nodes/subscripting.h. It may also be useful to read the array implementation in src/backend/utils/adt/arraysubs.c, or the simpler code in contrib/hstore/hstore_subs.c. Additional information appears in Array Types below. ๐
Okay so the details of your new type's internal representation are only known to the I/O functions and the other functions you create to work with the type. But there are several properties of that internal representation that must be declared to PostgreSQL. Foremost of these is internallength. Base data types can be:
- fixed-length โ in which case
internallengthis a positive integer, or - variable-length โ indicated by setting
internallengthtoVARIABLE. (Internally, this is represented by settingtyplento-1.)
The internal representation of all variable-length types must start with a 4-byte integer giving the total length of this value of the type. (Note that the length field is often encoded, as described in Section 66.2; it's unwise to access it directly. ๐)
The optional flag PASSEDBYVALUE indicates that values of this data type are passed by value, rather than by reference. Types passed by value must be fixed-length, and their internal representation cannot be larger than the size of the Datum type (4 bytes on some machines, 8 bytes on others). ๐
The alignment parameter specifies the storage alignment required for the data type. The allowed values equate to alignment on 1, 2, 4, or 8 byte boundaries. Note that variable-length types must have an alignment of at least 4, since they necessarily contain an int4 as their first component.
The storage parameter lets you select storage strategies for variable-length data types. (Only plain is allowed for fixed-length types.) Here's the rundown:
plainโ specifies that data of the type will always be stored in-line and not compressed.extendedโ specifies that the system will first try to compress a long data value, and will move the value out of the main table row if it's still too long.externalโ allows the value to be moved out of the main table, but the system will not try to compress it.mainโ allows compression, but discourages moving the value out of the main table. (Data items with this storage strategy might still be moved out of the main table if there is no other way to make a row fit, but they will be kept in the main table preferentially overextendedandexternalitems.)
All storage values other than plain imply that the functions of the data type can handle values that have been toasted, as described in Section 66.2 and Section 36.13.1. The specific other value given merely determines the default TOAST storage strategy for columns of a toastable data type; users can pick other strategies for individual columns using ALTER TABLE SET STORAGE. ๐๐ฅ
The like_type parameter gives you an alternative method for specifying the basic representation properties of a data type: copy them from some existing type. The values of internallength, passedbyvalue, alignment, and storage are copied from the named type. (It is possible, though usually undesirable, to override some of these values by specifying them along with the LIKE clause.) Specifying representation this way is especially useful when the low-level implementation of the new type "piggybacks" on an existing type in some fashion. ๐ท
The category and preferred parameters can be used to help control which implicit cast will be applied in ambiguous situations. Each data type belongs to a category named by a single ASCII character, and each type is either "preferred" or not within its category. The parser will prefer casting to preferred types (but only from other types within the same category) when this rule is helpful in resolving overloaded functions or operators. For more details see Chapter 10.
For types that have no implicit casts to or from any other types, it is sufficient to leave these settings at the defaults. However, for a group of related types that have implicit casts, it's often helpful to mark them all as belonging to a category and select one or two of the "most general" types as being preferred within the category. The category parameter is especially useful when adding a user-defined type to an existing built-in category, such as the numeric or string types. But wait, there's more: it's also possible to create new entirely-user-defined type categories. Select any ASCII character other than an upper-case letter to name such a category. ๐ค
A default value can be specified, in case a user wants columns of the data type to default to something other than the null value. Specify the default with the DEFAULT key word. (Such a default can be overridden by an explicit DEFAULT clause attached to a particular column.) ๐ซ
To indicate that a type is a fixed-length array type, specify the type of the array elements using the ELEMENT key word. For example, to define an array of 4-byte integers (int4), specify ELEMENT = int4. For more details, see Array Types below.
To indicate the delimiter to be used between values in the external representation of arrays of this type, delimiter can be set to a specific character. The default delimiter is the comma (,). Note that the delimiter is associated with the array element type, not the array type itself. ๐ฏ
If the optional Boolean parameter collatable is true, column definitions and expressions of the type may carry collation information through use of the COLLATE clause. It's up to the implementations of the functions operating on the type to actually make use of the collation information; this does not happen automatically merely by marking the type collatable. so don't expect magic, bestie โจ
๐ Array Types ๐
Whenever a user-defined type is created, PostgreSQL automatically creates an associated array type, whose name consists of the element type's name prepended with an underscore, and truncated if necessary to keep it less than NAMEDATALEN bytes long. (If the name so generated collides with an existing type name, the process is repeated until a non-colliding name is found.) This implicitly-created array type is variable length and uses the built-in input and output functions array_in and array_out. Furthermore, this type is what the system uses for constructs such as ARRAY[] over the user-defined type. The array type tracks any changes in its element type's owner or schema, and is dropped if the element type is. ๐ฏ
You might reasonably ask why there is an ELEMENT option, if the system makes the correct array type automatically. The main case where it's useful to use ELEMENT is when you're making a fixed-length type that happens to be internally an array of a number of identical things, and you want to allow these things to be accessed directly by subscripting, in addition to whatever operations you plan to provide for the type as a whole. For example, type point is represented as just two floating-point numbers, which can be accessed using point[0] and point[1]. Note that this facility only works for fixed-length types whose internal form is exactly a sequence of identical fixed-length fields. For historical reasons (i.e., this is clearly wrong but it's far too late to change it ๐), subscripting of fixed-length array types starts from zero, rather than from one as for variable-length arrays. ๐
Specifying the SUBSCRIPT option allows a data type to be subscripted, even though the system does not otherwise regard it as an array type. The behavior just described for fixed-length arrays is actually implemented by the SUBSCRIPT handler function raw_array_subscript_handler, which is used automatically if you specify ELEMENT for a fixed-length type without also writing SUBSCRIPT.
When specifying a custom SUBSCRIPT function, it is not necessary to specify ELEMENT unless the SUBSCRIPT handler function needs to consult typelem to find out what to return. Be aware that specifying ELEMENT causes the system to assume that the new type contains, or is somehow physically dependent on, the element type; thus for example changing properties of the element type won't be allowed if there are any columns of the dependent type. โ ๏ธ
๐ PARAMETERS ๐
okay bestie, here's the full lineup of every knob and dial you can turn in CREATE TYPE. no skipping, we're doing all of them ๐
nameโ the name of the type you're creating, and yeah it can be schema-qualified if you wanna be specific about where it lives ๐attribute_nameโ the name of an attribute (aka a column, same thing) inside your composite type โจdata_typeโ the name of an existing data type that's gonna become one of the columns in your composite type. it's giving "reuse, recycle" โป๏ธcollationโ the name of an existing collation to associate with a column of a composite type, or with a range type. sorting vibes, basically ๐labelโ a string literal that represents the textual label tied to one value of an enum type. like'new'or'closed', yk? ๐ท๏ธsubtypeโ the name of the element type that your range type is gonna represent ranges of. the main character of the range, fr ๐ฆsubtype_operator_classโ the name of a b-tree operator class for the subtype. yes b-tree, not the vibe tree ๐ณcanonical_functionโ the name of the canonicalization function for the range type. it makes things canonical, slay ๐subtype_diff_functionโ the name of a difference function for the subtype. math girlies rise ๐งฎmultirange_type_nameโ the name of the corresponding multirange type. range's plus-one ๐input_functionโ a function that converts data from the type's external textual form into its internal form. glow-up, textual edition โจoutput_functionโ a function that converts data from the type's internal form to its external textual form. the reverse glow-up ๐receive_functionโ a function that converts data from the type's external binary form to its internal form. binary bestie ๐คsend_functionโ a function that converts data from the type's internal form to its external binary form. bye binary babe ๐type_modifier_input_functionโ a function that converts an array of modifier(s) for the type into internal form. modifiers? more like modi-fine ๐type_modifier_output_functionโ a function that converts the internal form of the type's modifier(s) to external textual form. okay work ๐ซถanalyze_functionโ a function that performs statistical analysis for the data type. she's doing the math so you don't have to ๐subscript_functionโ a function that defines what subscripting a value of the data type does.arr[1]energy, iykyk ๐ขinternallengthโ a numeric constant that specifies the length in bytes of the new type's internal representation. the default assumption is that it's variable-length. so if you don't say anything, it's giving "variable" ๐ซalignmentโ the storage alignment requirement of the data type. if you specify it, it has to bechar,int2,int4, ordouble; the default isint4. pick your alignment, bestie ๐ฏstorageโ the storage strategy for the data type. if specified, it must beplain,external,extended, ormain; the default isplain. plain and simple, literally ๐ฆlike_typeโ the name of an existing data type that your new type will have the same representation as. the values ofinternallength,passedbyvalue,alignment, andstorageget copied from that type, unless you override them by explicitly specifying something else in thisCREATE TYPEcommand. copy-paste but make it intentional ๐categoryโ the category code (a single ASCII character) for this type. the default is'U'for "user-defined type". other standard category codes can be found in Table 52.65. you can also choose other ASCII characters to create custom categories. be unique, be a category of one ๐preferredโtrueif this type is a preferred type within its type category, elsefalse. the default isfalse. be very careful about creating a new preferred type within an existing type category, because this could cause surprising changes in behavior. โ ๏ธ seriously, not a drill โ ๏ธdefaultโ the default value for the data type. if you omit this, the default is null. the void, the nothing, the absence ๐ณ๏ธelementโ the type being created is an array, and this specifies the type of the array elements. so meta ๐ฆdelimiterโ the delimiter character to be used between values in arrays made of this type. comma, semicolon, whatever you vibe with ๐collatableโtrueif this type's operations can use collation information. the default isfalse. collation nation ๐
๐ NOTES ๐
okay so real talk, here's the tea โ
Because there are no restrictions on use of a data type once it's been created, creating a base type or range type is tantamount to granting public execute permission on the functions mentioned in the type definition. this is usually not an issue for the sorts of functions that are useful in a type definition. but you might want to think twice before designing a type in a way that would require "secret" information to be used while converting it to or from external form. ๐ secrets are not safe here, bestie.
Before PostgreSQL version 8.3, the name of a generated array type was always exactly the element type's name with one underscore character (_) prepended. (type names were therefore restricted in length to one fewer character than other names.) while this is still usually the case, the array type name may vary from this in case of maximum-length names or collisions with user type names that begin with underscore. writing code that depends on this convention is therefore deprecated. instead, use pg_type.typarray to locate the array type associated with a given type. no cap, do it the new way ๐ซ
It may be advisable to avoid using type and table names that begin with underscore. while the server will change generated array type names to avoid collisions with user-given names, there is still risk of confusion, particularly with old client software that may assume that type names beginning with underscores always represent arrays. just... don't start with underscore, it's giving chaos ๐ช๏ธ
Before PostgreSQL version 8.2, the shell-type creation syntax CREATE TYPE name did not exist. the way to create a new base type was to create its input function first. in this approach, PostgreSQL will first see the name of the new data type as the return type of the input function. the shell type is implicitly created in this situation, and then it can be referenced in the definitions of the remaining I/O functions. this approach still works, but is deprecated and might be disallowed in some future release. also, to avoid accidentally cluttering the catalogs with shell types as a result of simple typos in function definitions, a shell type will only be made this way when the input function is written in C. so like, it's a legacy thing, don't @ me ๐
In PostgreSQL version 16 and later, it is desirable for base types' input functions to return "soft" errors using the new errsave()/ereturn() mechanism, rather than throwing ereport() exceptions as in previous versions. see src/backend/utils/fmgr/README for more information. soft launch your errors, periodt โจ
๐ EXAMPLES ๐
This example creates a composite type and uses it in a function definition:
CREATE TYPE compfoo AS (f1 int, f2 text);
CREATE FUNCTION getfoo() RETURNS SETOF compfoo AS $$
SELECT fooid, fooname FROM foo
$$ LANGUAGE SQL;
This example creates an enumerated type and uses it in a table definition:
CREATE TYPE bug_status AS ENUM ('new', 'open', 'closed');
CREATE TABLE bug (
id serial,
description text,
status bug_status
);
This example creates a range type:
CREATE TYPE float8_range AS RANGE (subtype = float8, subtype_diff = float8mi);
This example creates the base data type box and then uses the type in a table definition:
CREATE TYPE box;
CREATE FUNCTION my_box_in_function(cstring) RETURNS box AS ... ;
CREATE FUNCTION my_box_out_function(box) RETURNS cstring AS ... ;
CREATE TYPE box (
INTERNALLENGTH = 16,
INPUT = my_box_in_function,
OUTPUT = my_box_out_function
);
CREATE TABLE myboxes (
id integer,
description box
);
If the internal structure of box were an array of four float4 elements, we might instead use:
CREATE TYPE box (
INTERNALLENGTH = 16,
INPUT = my_box_in_function,
OUTPUT = my_box_out_function,
ELEMENT = float4
);
which would allow a box value's component numbers to be accessed by subscripting. otherwise the type behaves the same as before. so it's the same but with โจsubscript accessโจ
This example creates a large object type and uses it in a table definition:
CREATE TYPE bigobj (
INPUT = lo_filein, OUTPUT = lo_fileout,
INTERNALLENGTH = VARIABLE
);
CREATE TABLE big_objs (
id integer,
obj bigobj
);
More examples, including suitable input and output functions, are in Section 36.13. go read, bestie ๐
๐ซถ COMPATIBILITY ๐ซถ
The first form of the CREATE TYPE command, which creates a composite type, conforms to the SQL standard. the other forms are PostgreSQL extensions. the CREATE TYPE statement in the SQL standard also defines other forms that are not implemented in PostgreSQL. so like, we're standard-adjacent but also extra ๐
The ability to create a composite type with zero attributes is a PostgreSQL-specific deviation from the standard (analogous to the same case in CREATE TABLE). zero attributes? bold. iconic. very PostgreSQL ๐
๐ SEE ALSO ๐
ALTER TYPE(ALTER_TYPE(7))CREATE DOMAIN(CREATE_DOMAIN(7))CREATE FUNCTION(CREATE_FUNCTION(7))DROP TYPE(DROP_TYPE(7))
and that's the whole page, bestie! this was PostgreSQL 18.6, dated 2026, and the page is CREATE TYPE(7). mwah ๐ go make some types, you absolute legend ๐
๐ฆ where this page comes from
- opensuse-leap 16.0: postgresql18 18.6-160000.1.1 ยท PostgreSQL
- opensuse-leap 16.0: postgresql18 18.6-160000.1.1 ยท PostgreSQL
- opensuse-leap 16.0: postgresql18 18.6-160000.1.1 ยท PostgreSQL
- opensuse-leap 16.0: postgresql18 18.6-160000.1.1 ยท PostgreSQL
- ๐ girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms