Sub topic 7
How Operators and Functions Pick Argument Types
This chapter assumes you know basic SQL and can run queries in psql. It also assumes you have read the earlier chapters on cast syntax, literal types and cast contexts (implicit, assignment, explicit). Here you will learn how PostgreSQL chooses which operator or function to run when you write a + b or f(x, y). It covers where an implicit conversion fits in, why some calls fail with "does not exist", and how to debug them.
Why resolution exists
PostgreSQL has many operators and functions with the same name. The + operator alone is defined for integer + integer, bigint + bigint, numeric + numeric, date + integer and more. Each is a separate entry in the pg_operator catalog. Functions are overloaded in the same way, as entries in pg_proc.
When you write 1 + 2.5, the parser must pick exactly one entry. This choice is made at parse time from the argument types, never from the values. Once the entry is chosen, the parser inserts any implicit casts it needs. If it cannot choose, you get one of two errors:
operator does not exist: integer + text. No candidate fits, even after implicit casts.operator is not unique: unknown + unknown. Several candidates fit equally well.
The operator resolution steps
The rules are applied in order, and the first step that yields a single answer wins.
- Collect every operator with the given name and number of arguments that is visible through
search_path. - If a candidate matches the argument types exactly, use it. If one argument is an untyped literal (
unknown), assume it has the same type as the other argument for this check. - Otherwise, discard candidates that cannot accept the arguments through implicit casts. An untyped literal is assumed convertible to anything. Domains are treated as their base types.
- If several candidates remain, narrow them down:
- Keep those with the most exactly matching argument types.
- Keep those that accept a preferred type in the most positions that need conversion.
- For positions that hold an untyped literal, prefer the string category, because literals look like strings. Otherwise, use the category that all remaining candidates agree on.
- If exactly one candidate is left, use it. If none or several are left, raise an error.
A preferred type is the type marked as preferred within its category. For example, float8 is preferred among the numeric types, text among the string types, and timestamptz among the date/time types. You can see these markings in pg_type:
SELECT typname, typcategory, typispreferred
FROM pg_type
WHERE typname IN ('int4', 'numeric', 'float8', 'text', 'timestamptz')
ORDER BY typname;Worked example: integer plus numeric
No integer + numeric operator exists. You can check this by listing the operators whose left side is int4:
SELECT oprname, oprleft::regtype, oprright::regtype, oprresult::regtype
FROM pg_operator
WHERE oprname = '+'
AND oprleft = 'int4'::regtype
ORDER BY oprright::regtype::text;So 1 + 2.5 goes through the narrowing steps:
- The literal
1isintegerand2.5isnumeric, so there is no exact match. int4 + int4is discarded, becausenumerictointegeris only an assignment cast.numeric + numericstays, becauseintegertonumericis implicit.float8 + float8also stays, because both inputs convert implicitly tofloat8.numeric + numerichas one exact match andfloat8 + float8has none, sonumeric + numericwins.
SELECT pg_typeof(1 + 2.5) AS numeric_result,
pg_typeof(1::smallint + 1) AS small_plus_int,
pg_typeof(1 + 3000000000) AS int_plus_bigint;The three results are numeric, integer and bigint. In each case the narrower type is promoted through an implicit cast.
When exact matches do not break the tie, preferred types do. The ^ operator exists for float8 and numeric only. For 2 ^ 3, both candidates accept integer implicitly and neither matches exactly. The preferred type float8 wins:
SELECT 2 ^ 3 AS result, pg_typeof(2 ^ 3) AS type;The result is 8 with type double precision.
Untyped literals
An untyped literal such as '2' has type unknown until resolution gives it a type. This explains the pair of queries from the chapter on literals:
SELECT 1 + '2' AS ok;
SELECT 1 + '2'::text AS fails;In the first query, '2' is unknown, so step 2 assumes it is integer and integer + integer matches exactly. In the second query, '2'::text has a real type. No integer + text operator exists, and text to integer is not an implicit cast, so the query fails.
When both sides are unknown, the string category rule applies. 'abc' || 'def' resolves to text || text, but '1' + '2' is ambiguous:
SELECT 'abc' || 'def' AS joined;
SELECT '1' + '2' AS ambiguous; -- ERROR: operator is not unique: unknown + unknownThis catches people when they move a literal into a CTE:
WITH t AS (SELECT '2' AS n)
SELECT 1 + n FROM t; -- ERROR: operator does not exist: integer + text
WITH t AS (SELECT '2' AS n)
SELECT 1 + n::integer FROM t; -- works: 3Function resolution
Function calls follow nearly the same rules, with a few additions:
- If a function has default arguments, candidates are matched as if the defaults were supplied.
VARIADICfunctions are matched as if the variadic argument were expanded.- If two candidates have identical argument types in different schemas, the one in the earlier
search_pathschema wins. - A call with one argument whose function name is a type name, such as
integer('42'), is treated as a cast request.
For example, round(4, 4) resolves cleanly. Only round(numeric, integer) takes two arguments, and the first argument converts implicitly from integer to numeric:
SELECT round(4, 4) AS r, pg_typeof(round(4, 4)) AS type;The result is 4.0000 with type numeric.
The next call shows the limit of implicit casts. The integer to text conversion is only an assignment cast, so it is not applied inside function arguments:
SELECT upper('42') AS works;
SELECT upper(42) AS fails; -- ERROR: function upper(integer) does not existThe error comes with a hint: "No function matches the given name and argument types. You might need to add explicit type casts." The fix is upper(42::text).
Debugging a resolution failure
- Check the real types with
pg_typeof(expr)for each argument. An argument you think is an integer is oftentextornumeric. - List the candidates with
\do+ +or\df+ upperin psql, or querypg_operatorandpg_procdirectly. - Look up the cast between your type and the candidate's type in
pg_cast. Onlycastcontext = 'i'allows resolution to apply the conversion for you. - Add an explicit cast on the argument that is wrong. Cast the value, not the whole expression, so the intended operator is picked.
Summary of outcomes
| Expression | Matching step | Result type |
|---|---|---|
| `1 + '2'` | Exact match, literal assumed `integer` | `integer` |
| `1 + 2.5` | Implicit cast, exact-match count | `numeric` |
| `2 ^ 3` | Preferred type | `double precision` |
| `'1' + '2'` | Ambiguous | error: not unique |
| `1 + '2'::text` | No implicit cast from `text` | error: does not exist |
Exercise
The query WITH t AS (SELECT '5' AS n) SELECT n + 1 FROM t; fails. Explain why, using the resolution rules, and give two ways to fix it.
Show answer
Inside the CTE, the unknown literal '5' is resolved to text when the select list is finished, so n is a text column. The outer query then looks for text + integer. No such operator exists, and text to integer is not an implicit cast, so it fails with "operator does not exist: text + integer". Fix 1: cast the column, SELECT n::integer + 1 FROM t. Fix 2: type the literal in the CTE, SELECT '5'::integer AS n or SELECT 5 AS n.
Exercise
SELECT pg_typeof(1::smallint + 1); returns integer, not smallint. Which resolution step produces this, and why does no smallint + integer operator need to exist?
Show answer
There is no exact match for smallint + integer, so the parser discards candidates that need non-implicit casts. The operator integer + integer remains, because smallint to integer is an implicit cast, and it has an exact match for the second argument. It is chosen, the smallint is cast to integer, and the result is integer.