{
    "content": [
        {
            "type": "text",
            "text": "# CREATE_CAST(7) (man)\n\n**Summary:** CREATECAST - define a new cast\n\n**Synopsis:** CREATE CAST (sourcetype AS targettype)\nWITH FUNCTION functionname [ (argumenttype [, ...]) ]\n[ AS ASSIGNMENT | AS IMPLICIT ]\nCREATE CAST (sourcetype AS targettype)\nWITHOUT FUNCTION\n[ AS ASSIGNMENT | AS IMPLICIT ]\nCREATE CAST (sourcetype AS targettype)\nWITH INOUT\n[ AS ASSIGNMENT | AS IMPLICIT ]\n\n## Examples\n\n- `To create an assignment cast from type bigint to type int4 using the function int4(bigint):`\n- `CREATE CAST (bigint AS int4) WITH FUNCTION int4(bigint) AS ASSIGNMENT;`\n- `(This cast is already predefined in the system.)`\n\n## See Also\n\n- CREATEFUNCTION(7)\n- CREATETYPE(7)\n- DROPCAST(7)\n- CAST(7)\n\n## Section Outline\n\n- **NAME** (2 lines)\n- **SYNOPSIS** (12 lines)\n- **DESCRIPTION** (78 lines)\n- **PARAMETERS** (54 lines)\n- **NOTES** (44 lines)\n- **EXAMPLES** (6 lines)\n- **COMPATIBILITY** (4 lines)\n- **SEE ALSO** (5 lines)\n\n## Full Content\n\n### NAME\n\nCREATECAST - define a new cast\n\n### SYNOPSIS\n\nCREATE CAST (sourcetype AS targettype)\nWITH FUNCTION functionname [ (argumenttype [, ...]) ]\n[ AS ASSIGNMENT | AS IMPLICIT ]\n\nCREATE CAST (sourcetype AS targettype)\nWITHOUT FUNCTION\n[ AS ASSIGNMENT | AS IMPLICIT ]\n\nCREATE CAST (sourcetype AS targettype)\nWITH INOUT\n[ AS ASSIGNMENT | AS IMPLICIT ]\n\n### DESCRIPTION\n\nCREATE CAST defines a new cast. A cast specifies how to perform a conversion between two data\ntypes. For example,\n\nSELECT CAST(42 AS float8);\n\nconverts the integer constant 42 to type float8 by invoking a previously specified function,\nin this case float8(int4). (If no suitable cast has been defined, the conversion fails.)\n\nTwo types can be binary coercible, which means that the conversion can be performed “for\nfree” without invoking any function. This requires that corresponding values use the same\ninternal representation. For instance, the types text and varchar are binary coercible both\nways. Binary coercibility is not necessarily a symmetric relationship. For example, the cast\nfrom xml to text can be performed for free in the present implementation, but the reverse\ndirection requires a function that performs at least a syntax check. (Two types that are\nbinary coercible both ways are also referred to as binary compatible.)\n\nYou can define a cast as an I/O conversion cast by using the WITH INOUT syntax. An I/O\nconversion cast is performed by invoking the output function of the source data type, and\npassing the resulting string to the input function of the target data type. In many common\ncases, this feature avoids the need to write a separate cast function for conversion. An I/O\nconversion cast acts the same as a regular function-based cast; only the implementation is\ndifferent.\n\nBy default, a cast can be invoked only by an explicit cast request, that is an explicit\nCAST(x AS typename) or x::typename construct.\n\nIf the cast is marked AS ASSIGNMENT then it can be invoked implicitly when assigning a value\nto a column of the target data type. For example, supposing that foo.f1 is a column of type\ntext, then:\n\nINSERT INTO foo (f1) VALUES (42);\n\nwill be allowed if the cast from type integer to type text is marked AS ASSIGNMENT, otherwise\nnot. (We generally use the term assignment cast to describe this kind of cast.)\n\nIf the cast is marked AS IMPLICIT then it can be invoked implicitly in any context, whether\nassignment or internally in an expression. (We generally use the term implicit cast to\ndescribe this kind of cast.) For example, consider this query:\n\nSELECT 2 + 4.0;\n\nThe parser initially marks the constants as being of type integer and numeric respectively.\nThere is no integer + numeric operator in the system catalogs, but there is a numeric +\nnumeric operator. The query will therefore succeed if a cast from integer to numeric is\navailable and is marked AS IMPLICIT — which in fact it is. The parser will apply the implicit\ncast and resolve the query as if it had been written\n\nSELECT CAST ( 2 AS numeric ) + 4.0;\n\nNow, the catalogs also provide a cast from numeric to integer. If that cast were marked AS\nIMPLICIT — which it is not — then the parser would be faced with choosing between the above\ninterpretation and the alternative of casting the numeric constant to integer and applying\nthe integer + integer operator. Lacking any knowledge of which choice to prefer, it would\ngive up and declare the query ambiguous. The fact that only one of the two casts is implicit\nis the way in which we teach the parser to prefer resolution of a mixed numeric-and-integer\nexpression as numeric; there is no built-in knowledge about that.\n\nIt is wise to be conservative about marking casts as implicit. An overabundance of implicit\ncasting paths can cause PostgreSQL to choose surprising interpretations of commands, or to be\nunable to resolve commands at all because there are multiple possible interpretations. A good\nrule of thumb is to make a cast implicitly invokable only for information-preserving\ntransformations between types in the same general type category. For example, the cast from\nint2 to int4 can reasonably be implicit, but the cast from float8 to int4 should probably be\nassignment-only. Cross-type-category casts, such as text to int4, are best made\nexplicit-only.\n\nNote\nSometimes it is necessary for usability or standards-compliance reasons to provide\nmultiple implicit casts among a set of types, resulting in ambiguity that cannot be\navoided as above. The parser has a fallback heuristic based on type categories and\npreferred types that can help to provide desired behavior in such cases. See CREATE TYPE\n(CREATETYPE(7)) for more information.\n\nTo be able to create a cast, you must own the source or the target data type and have USAGE\nprivilege on the other type. To create a binary-coercible cast, you must be superuser. (This\nrestriction is made because an erroneous binary-coercible cast conversion can easily crash\nthe server.)\n\n### PARAMETERS\n\nsourcetype\nThe name of the source data type of the cast.\n\ntargettype\nThe name of the target data type of the cast.\n\nfunctionname[(argumenttype [, ...])]\nThe function used to perform the cast. The function name can be schema-qualified. If it\nis not, the function will be looked up in the schema search path. The function's result\ndata type must match the target type of the cast. Its arguments are discussed below. If\nno argument list is specified, the function name must be unique in its schema.\n\nWITHOUT FUNCTION\nIndicates that the source type is binary-coercible to the target type, so no function is\nrequired to perform the cast.\n\nWITH INOUT\nIndicates that the cast is an I/O conversion cast, performed by invoking the output\nfunction of the source data type, and passing the resulting string to the input function\nof the target data type.\n\nAS ASSIGNMENT\nIndicates that the cast can be invoked implicitly in assignment contexts.\n\nAS IMPLICIT\nIndicates that the cast can be invoked implicitly in any context.\n\nCast implementation functions can have one to three arguments. The first argument type must\nbe identical to or binary-coercible from the cast's source type. The second argument, if\npresent, must be type integer; it receives the type modifier associated with the destination\ntype, or -1 if there is none. The third argument, if present, must be type boolean; it\nreceives true if the cast is an explicit cast, false otherwise. (Bizarrely, the SQL standard\ndemands different behaviors for explicit and implicit casts in some cases. This argument is\nsupplied for functions that must implement such casts. It is not recommended that you design\nyour own data types so that this matters.)\n\nThe return type of a cast function must be identical to or binary-coercible to the cast's\ntarget type.\n\nOrdinarily a cast must have different source and target data types. However, it is allowed to\ndeclare a cast with identical source and target types if it has a cast implementation\nfunction with more than one argument. This is used to represent type-specific length coercion\nfunctions in the system catalogs. The named function is used to coerce a value of the type to\nthe type modifier value given by its second argument.\n\nWhen a cast has different source and target types and a function that takes more than one\nargument, it supports converting from one type to another and applying a length coercion in a\nsingle step. When no such entry is available, coercion to a type that uses a type modifier\ninvolves two cast steps, one to convert between data types and a second to apply the\nmodifier.\n\nA cast to or from a domain type currently has no effect. Casting to or from a domain uses the\ncasts associated with its underlying type.\n\n### NOTES\n\nUse DROP CAST to remove user-defined casts.\n\nRemember that if you want to be able to convert types both ways you need to declare casts\nboth ways explicitly.\n\nIt is normally not necessary to create casts between user-defined types and the standard\nstring types (text, varchar, and char(n), as well as user-defined types that are defined to\nbe in the string category).  PostgreSQL provides automatic I/O conversion casts for that. The\nautomatic casts to string types are treated as assignment casts, while the automatic casts\nfrom string types are explicit-only. You can override this behavior by declaring your own\ncast to replace an automatic cast, but usually the only reason to do so is if you want the\nconversion to be more easily invokable than the standard assignment-only or explicit-only\nsetting. Another possible reason is that you want the conversion to behave differently from\nthe type's I/O function; but that is sufficiently surprising that you should think twice\nabout whether it's a good idea. (A small number of the built-in types do indeed have\ndifferent behaviors for conversions, mostly because of requirements of the SQL standard.)\n\nWhile not required, it is recommended that you continue to follow this old convention of\nnaming cast implementation functions after the target data type. Many users are used to being\nable to cast data types using a function-style notation, that is typename(x). This notation\nis in fact nothing more nor less than a call of the cast implementation function; it is not\nspecially treated as a cast. If your conversion functions are not named to support this\nconvention then you will have surprised users. Since PostgreSQL allows overloading of the\nsame function name with different argument types, there is no difficulty in having multiple\nconversion functions from different types that all use the target type's name.\n\nNote\nActually the preceding paragraph is an oversimplification: there are two cases in which a\nfunction-call construct will be treated as a cast request without having matched it to an\nactual function. If a function call name(x) does not exactly match any existing function,\nbut name is the name of a data type and pgcast provides a binary-coercible cast to this\ntype from the type of x, then the call will be construed as a binary-coercible cast. This\nexception is made so that binary-coercible casts can be invoked using functional syntax,\neven though they lack any function. Likewise, if there is no pgcast entry but the cast\nwould be to or from a string type, the call will be construed as an I/O conversion cast.\nThis exception allows I/O conversion casts to be invoked using functional syntax.\n\nNote\nThere is also an exception to the exception: I/O conversion casts from composite types to\nstring types cannot be invoked using functional syntax, but must be written in explicit\ncast syntax (either CAST or :: notation). This exception was added because after the\nintroduction of automatically-provided I/O conversion casts, it was found too easy to\naccidentally invoke such a cast when a function or column reference was intended.\n\n### EXAMPLES\n\nTo create an assignment cast from type bigint to type int4 using the function int4(bigint):\n\nCREATE CAST (bigint AS int4) WITH FUNCTION int4(bigint) AS ASSIGNMENT;\n\n(This cast is already predefined in the system.)\n\n### COMPATIBILITY\n\nThe CREATE CAST command conforms to the SQL standard, except that SQL does not make\nprovisions for binary-coercible types or extra arguments to implementation functions.  AS\nIMPLICIT is a PostgreSQL extension, too.\n\n### SEE ALSO\n\nCREATE FUNCTION (CREATEFUNCTION(7)), CREATE TYPE (CREATETYPE(7)), DROP CAST (DROPCAST(7))\n\n\n\nPostgreSQL 14.23                                2026                                  CREATE CAST(7)\n\n"
        }
    ],
    "structuredContent": {
        "command": "CREATE_CAST",
        "section": "7",
        "mode": "man",
        "summary": "CREATECAST - define a new cast",
        "synopsis": "CREATE CAST (sourcetype AS targettype)\nWITH FUNCTION functionname [ (argumenttype [, ...]) ]\n[ AS ASSIGNMENT | AS IMPLICIT ]\nCREATE CAST (sourcetype AS targettype)\nWITHOUT FUNCTION\n[ AS ASSIGNMENT | AS IMPLICIT ]\nCREATE CAST (sourcetype AS targettype)\nWITH INOUT\n[ AS ASSIGNMENT | AS IMPLICIT ]",
        "flags": [],
        "examples": [
            "To create an assignment cast from type bigint to type int4 using the function int4(bigint):",
            "CREATE CAST (bigint AS int4) WITH FUNCTION int4(bigint) AS ASSIGNMENT;",
            "(This cast is already predefined in the system.)"
        ],
        "see_also": [
            {
                "name": "CREATEFUNCTION",
                "section": "7",
                "url": "https://www.chedong.com/phpMan.php/man/CREATEFUNCTION/7/json"
            },
            {
                "name": "CREATETYPE",
                "section": "7",
                "url": "https://www.chedong.com/phpMan.php/man/CREATETYPE/7/json"
            },
            {
                "name": "DROPCAST",
                "section": "7",
                "url": "https://www.chedong.com/phpMan.php/man/DROPCAST/7/json"
            },
            {
                "name": "CAST",
                "section": "7",
                "url": "https://www.chedong.com/phpMan.php/man/CAST/7/json"
            }
        ],
        "section_outline": [
            {
                "name": "NAME",
                "lines": 2,
                "subsections": []
            },
            {
                "name": "SYNOPSIS",
                "lines": 12,
                "subsections": []
            },
            {
                "name": "DESCRIPTION",
                "lines": 78,
                "subsections": []
            },
            {
                "name": "PARAMETERS",
                "lines": 54,
                "subsections": []
            },
            {
                "name": "NOTES",
                "lines": 44,
                "subsections": []
            },
            {
                "name": "EXAMPLES",
                "lines": 6,
                "subsections": []
            },
            {
                "name": "COMPATIBILITY",
                "lines": 4,
                "subsections": []
            },
            {
                "name": "SEE ALSO",
                "lines": 5,
                "subsections": []
            }
        ]
    }
}