{"Entry":{"collection":"language","key":"sql","name":"sql","aliases":[],"metadata":{"aliases":[],"category":"Native function languages","content_hash":"e05eeb71be58ad1aae243e1b9ca1f486566131c8801650e317081c663d91f526","imported_at":"2026-09-30T00:40:44.378814+08:00","name":"sql","name_zh":"","slug":"sql","summary":"SQL-language functions"}},"Definition":{"Collection":"language","Key":"sql","SourceDatabase":"center","Version":"18","SourceTable":"procedural_language","SourceKey":"sql","SourceRevision":"555610c24d53e4316da5b7d3fc25c279d96856d5e0e23ee308c328c5fa881d9f","Facts":{"aliases":[],"attributes":{"handler":"","kind":"Native function language","trusted":"t","validator":"fmgr_sql_validator"},"catalog":{"descr":"SQL-language functions","lanacl":"_null_","laninline":"0","lanispl":"f","lanname":"sql","lanowner":"POSTGRES","lanplcallfoid":"0","lanpltrusted":"t","lanvalidator":"fmgr_sql_validator","oid":"14","oid_symbol":"SQLlanguageId"},"comparison_data":{"handler":"","kind":"Native function language","trusted":"t","validator":"fmgr_sql_validator"},"comparison_hash":"a4af9cf453d140d941e865b952c6a41e2b704a4b30cb77b61c1cdda8a77c5035","description":["SQL-language functions"],"facts":[{"label":"Kind","value":"Native function language"},{"label":"Trusted","value":"t"},{"label":"Validator","value":"fmgr_sql_validator"}],"manual_html":"\u003cdiv class=\"sect1\" id=\"XFUNC-SQL\"\u003e\n\u003cdiv class=\"titlepage\"\u003e\n\u003cdiv\u003e\n\u003cdiv\u003e\n\u003ch2 class=\"title\"\u003e36.5. Query Language (SQL) Functions \u003c/h2\u003e\n\u003c/div\u003e\n\u003c/div\u003e\n\u003c/div\u003e\n\n\u003cp\u003eSQL functions execute an arbitrary list of SQL statements, returning the result of the last query in the list. In the simple (non-set) case, the first row of the last query's result will be returned. (Bear in mind that \u003cspan class=\"quote\"\u003e“\u003cspan class=\"quote\"\u003ethe first row\u003c/span\u003e”\u003c/span\u003e of a multirow result is not well-defined unless you use \u003ccode class=\"literal\"\u003eORDER BY\u003c/code\u003e.) If the last query happens to return no rows at all, the null value will be returned.\u003c/p\u003e\n\u003cp\u003eAlternatively, an SQL function can be declared to return a set (that is, multiple rows) by specifying the function's return type as \u003ccode class=\"literal\"\u003eSETOF \u003cem class=\"replaceable\"\u003e\u003ccode\u003esometype\u003c/code\u003e\u003c/em\u003e\u003c/code\u003e, or equivalently by declaring it as \u003ccode class=\"literal\"\u003eRETURNS TABLE(\u003cem class=\"replaceable\"\u003e\u003ccode\u003ecolumns\u003c/code\u003e\u003c/em\u003e)\u003c/code\u003e. In this case all rows of the last query's result are returned. Further details appear below.\u003c/p\u003e\n\u003cp\u003eThe body of an SQL function must be a list of SQL statements separated by semicolons. A semicolon after the last statement is optional. Unless the function is declared to return \u003ccode class=\"type\"\u003evoid\u003c/code\u003e, the last statement must be a \u003ccode class=\"command\"\u003eSELECT\u003c/code\u003e, or an \u003ccode class=\"command\"\u003eINSERT\u003c/code\u003e, \u003ccode class=\"command\"\u003eUPDATE\u003c/code\u003e, \u003ccode class=\"command\"\u003eDELETE\u003c/code\u003e, or \u003ccode class=\"command\"\u003eMERGE\u003c/code\u003e that has a \u003ccode class=\"literal\"\u003eRETURNING\u003c/code\u003e clause.\u003c/p\u003e\n\u003cp\u003eAny collection of commands in the SQL language can be packaged together and defined as a function. Besides \u003ccode class=\"command\"\u003eSELECT\u003c/code\u003e queries, the commands can include data modification queries (\u003ccode class=\"command\"\u003eINSERT\u003c/code\u003e, \u003ccode class=\"command\"\u003eUPDATE\u003c/code\u003e, \u003ccode class=\"command\"\u003eDELETE\u003c/code\u003e, and \u003ccode class=\"command\"\u003eMERGE\u003c/code\u003e), as well as other SQL commands. (You cannot use transaction control commands, e.g., \u003ccode class=\"command\"\u003eCOMMIT\u003c/code\u003e, \u003ccode class=\"command\"\u003eSAVEPOINT\u003c/code\u003e, and some utility commands, e.g., \u003ccode class=\"literal\"\u003eVACUUM\u003c/code\u003e, in SQL functions.) However, the final command must be a \u003ccode class=\"command\"\u003eSELECT\u003c/code\u003e or have a \u003ccode class=\"literal\"\u003eRETURNING\u003c/code\u003e clause that returns whatever is specified as the function's return type. Alternatively, if you want to define an SQL function that performs actions but has no useful value to return, you can define it as returning \u003ccode class=\"type\"\u003evoid\u003c/code\u003e. For example, this function removes rows with negative salaries from the \u003ccode class=\"literal\"\u003eemp\u003c/code\u003e table:\u003c/p\u003e\n\u003cpre class=\"screen\"\u003eCREATE FUNCTION clean_emp() RETURNS void AS '\n    DELETE FROM emp\n        WHERE salary \u0026lt; 0;\n' LANGUAGE SQL;\n\nSELECT clean_emp();\n\n clean_emp\n-----------\n\n(1 row)\n\u003c/pre\u003e\n\u003cp\u003eYou can also write this as a procedure, thus avoiding the issue of the return type. For example:\u003c/p\u003e\n\u003cpre class=\"screen\"\u003eCREATE PROCEDURE clean_emp() AS '\n    DELETE FROM emp\n        WHERE salary \u0026lt; 0;\n' LANGUAGE SQL;\n\nCALL clean_emp();\n\u003c/pre\u003e\n\u003cp\u003eIn simple cases like this, the difference between a function returning \u003ccode class=\"type\"\u003evoid\u003c/code\u003e and a procedure is mostly stylistic. However, procedures offer additional functionality such as transaction control that is not available in functions. Also, procedures are SQL standard whereas returning \u003ccode class=\"type\"\u003evoid\u003c/code\u003e is a PostgreSQL extension.\u003c/p\u003e\n\u003cp\u003eThe syntax of the \u003ccode class=\"command\"\u003eCREATE FUNCTION\u003c/code\u003e command requires the function body to be written as a string constant. It is usually most convenient to use dollar quoting (see \u003ca class=\"xref\" href=\"/docs/18/sql-syntax-lexical.html#SQL-SYNTAX-DOLLAR-QUOTING\" title=\"4.1.2.4. Dollar-Quoted String Constants\"\u003eSection 4.1.2.4\u003c/a\u003e) for the string constant. If you choose to use regular single-quoted string constant syntax, you must double single quote marks (\u003ccode class=\"literal\"\u003e'\u003c/code\u003e) and backslashes (\u003ccode class=\"literal\"\u003e\\\u003c/code\u003e) (assuming escape string syntax) in the body of the function (see \u003ca class=\"xref\" href=\"/docs/18/sql-syntax-lexical.html#SQL-SYNTAX-STRINGS\" title=\"4.1.2.1. String Constants\"\u003eSection 4.1.2.1\u003c/a\u003e).\u003c/p\u003e\n\u003cdiv class=\"sect2\" id=\"XFUNC-SQL-FUNCTION-ARGUMENTS\"\u003e\n\u003cdiv class=\"titlepage\"\u003e\n\u003cdiv\u003e\n\u003cdiv\u003e\n\u003ch3 class=\"title\"\u003e36.5.1. Arguments for SQL Functions \u003c/h3\u003e\n\u003c/div\u003e\n\u003c/div\u003e\n\u003c/div\u003e\n\u003cp\u003eArguments of an SQL function can be referenced in the function body using either names or numbers. Examples of both methods appear below.\u003c/p\u003e\n\u003cp\u003eTo use a name, declare the function argument as having a name, and then just write that name in the function body. If the argument name is the same as any column name in the current SQL command within the function, the column name will take precedence. To override this, qualify the argument name with the name of the function itself, that is \u003ccode class=\"literal\"\u003e\u003cem class=\"replaceable\"\u003e\u003ccode\u003efunction_name\u003c/code\u003e\u003c/em\u003e.\u003cem class=\"replaceable\"\u003e\u003ccode\u003eargument_name\u003c/code\u003e\u003c/em\u003e\u003c/code\u003e. (If this would conflict with a qualified column name, again the column name wins. You can avoid the ambiguity by choosing a different alias for the table within the SQL command.)\u003c/p\u003e\n\u003cp\u003eIn the older numeric approach, arguments are referenced using the syntax \u003ccode class=\"literal\"\u003e$\u003cem class=\"replaceable\"\u003e\u003ccode\u003en\u003c/code\u003e\u003c/em\u003e\u003c/code\u003e: \u003ccode class=\"literal\"\u003e$1\u003c/code\u003e refers to the first input argument, \u003ccode class=\"literal\"\u003e$2\u003c/code\u003e to the second, and so on. This will work whether or not the particular argument was declared with a name.\u003c/p\u003e\n\u003cp\u003eIf an argument is of a composite type, then the dot notation, e.g., \u003ccode class=\"literal\"\u003e\u003cem class=\"replaceable\"\u003e\u003ccode\u003eargname\u003c/code\u003e\u003c/em\u003e.\u003cem class=\"replaceable\"\u003e\u003ccode\u003efieldname\u003c/code\u003e\u003c/em\u003e\u003c/code\u003e or \u003ccode class=\"literal\"\u003e$1.\u003cem class=\"replaceable\"\u003e\u003ccode\u003efieldname\u003c/code\u003e\u003c/em\u003e\u003c/code\u003e, can be used to access attributes of the argument. Again, you might need to qualify the argument's name with the function name to make the form with an argument name unambiguous.\u003c/p\u003e\n\u003cp\u003eSQL function arguments can only be used as data values, not as identifiers. Thus for example this is reasonable:\u003c/p\u003e\n\u003cpre class=\"programlisting\"\u003eINSERT INTO mytable VALUES ($1);\n\u003c/pre\u003e\n\u003cp\u003ebut this will not work:\u003c/p\u003e\n\u003cpre class=\"programlisting\"\u003eINSERT INTO $1 VALUES (42);\n\u003c/pre\u003e\n\u003cdiv class=\"note\"\u003e\n\u003ch3 class=\"title\"\u003eNote\u003c/h3\u003e\n\u003cp\u003eThe ability to use names to reference SQL function arguments was added in \u003cspan class=\"productname\"\u003ePostgreSQL\u003c/span\u003e 9.2. Functions to be used in older servers must use the \u003ccode class=\"literal\"\u003e$\u003cem class=\"replaceable\"\u003e\u003ccode\u003en\u003c/code\u003e\u003c/em\u003e\u003c/code\u003e notation.\u003c/p\u003e\n\u003c/div\u003e\n\u003c/div\u003e\n\u003cdiv class=\"sect2\" id=\"XFUNC-SQL-BASE-FUNCTIONS\"\u003e\n\u003cdiv class=\"titlepage\"\u003e\n\u003cdiv\u003e\n\u003cdiv\u003e\n\u003ch3 class=\"title\"\u003e36.5.2. SQL Functions on Base Types \u003c/h3\u003e\n\u003c/div\u003e\n\u003c/div\u003e\n\u003c/div\u003e\n\u003cp\u003eThe simplest possible SQL function has no arguments and simply returns a base type, such as \u003ccode class=\"type\"\u003einteger\u003c/code\u003e:\u003c/p\u003e\n\u003cpre class=\"screen\"\u003eCREATE FUNCTION one() RETURNS integer AS $$\n    SELECT 1 AS result;\n$$ LANGUAGE SQL;\n\n-- Alternative syntax for string literal:\nCREATE FUNCTION one() RETURNS integer AS '\n    SELECT 1 AS result;\n' LANGUAGE SQL;\n\nSELECT one();\n\n one\n-----\n   1\n\u003c/pre\u003e\n\u003cp\u003eNotice that we defined a column alias within the function body for the result of the function (with the name \u003ccode class=\"literal\"\u003eresult\u003c/code\u003e), but this column alias is not visible outside the function. Hence, the result is labeled \u003ccode class=\"literal\"\u003eone\u003c/code\u003e instead of \u003ccode class=\"literal\"\u003eresult\u003c/code\u003e.\u003c/p\u003e\n\u003cp\u003eIt is almost as easy to define SQL functions that take base types as arguments:\u003c/p\u003e\n\u003cpre class=\"screen\"\u003eCREATE FUNCTION add_em(x integer, y integer) RETURNS integer AS $$\n    SELECT x + y;\n$$ LANGUAGE SQL;\n\nSELECT add_em(1, 2) AS answer;\n\n answer\n--------\n      3\n\u003c/pre\u003e\n\u003cp\u003eAlternatively, we could dispense with names for the arguments and use numbers:\u003c/p\u003e\n\u003cpre class=\"screen\"\u003eCREATE FUNCTION add_em(integer, integer) RETURNS integer AS $$\n    SELECT $1 + $2;\n$$ LANGUAGE SQL;\n\nSELECT add_em(1, 2) AS answer;\n\n answer\n--------\n      3\n\u003c/pre\u003e\n\u003cp\u003eHere is a more useful function, which might be used to debit a bank account:\u003c/p\u003e\n\u003cpre class=\"programlisting\"\u003eCREATE FUNCTION tf1 (accountno integer, debit numeric) RETURNS numeric AS $$\n    UPDATE bank\n        SET balance = balance - debit\n        WHERE accountno = tf1.accountno;\n    SELECT 1;\n$$ LANGUAGE SQL;\n\u003c/pre\u003e\n\u003cp\u003eA user could execute this function to debit account 17 by $100.00 as follows:\u003c/p\u003e\n\u003cpre class=\"programlisting\"\u003eSELECT tf1(17, 100.0);\n\u003c/pre\u003e\n\u003cp\u003eIn this example, we chose the name \u003ccode class=\"literal\"\u003eaccountno\u003c/code\u003e for the first argument, but this is the same as the name of a column in the \u003ccode class=\"literal\"\u003ebank\u003c/code\u003e table. Within the \u003ccode class=\"command\"\u003eUPDATE\u003c/code\u003e command, \u003ccode class=\"literal\"\u003eaccountno\u003c/code\u003e refers to the column \u003ccode class=\"literal\"\u003ebank.accountno\u003c/code\u003e, so \u003ccode class=\"literal\"\u003etf1.accountno\u003c/code\u003e must be used to refer to the argument. We could of course avoid this by using a different name for the argument.\u003c/p\u003e\n\u003cp\u003eIn practice one would probably like a more useful result from the function than a constant 1, so a more likely definition is:\u003c/p\u003e\n\u003cpre class=\"programlisting\"\u003eCREATE FUNCTION tf1 (accountno integer, debit numeric) RETURNS numeric AS $$\n    UPDATE bank\n        SET balance = balance - debit\n        WHERE accountno = tf1.accountno;\n    SELECT balance FROM bank WHERE accountno = tf1.accountno;\n$$ LANGUAGE SQL;\n\u003c/pre\u003e\n\u003cp\u003ewhich adjusts the balance and returns the new balance. The same thing could be done in one command using \u003ccode class=\"literal\"\u003eRETURNING\u003c/code\u003e:\u003c/p\u003e\n\u003cpre class=\"programlisting\"\u003eCREATE FUNCTION tf1 (accountno integer, debit numeric) RETURNS numeric AS $$\n    UPDATE bank\n        SET balance = balance - debit\n        WHERE accountno = tf1.accountno\n    RETURNING balance;\n$$ LANGUAGE SQL;\n\u003c/pre\u003e\n\u003cp\u003eIf the final \u003ccode class=\"literal\"\u003eSELECT\u003c/code\u003e or \u003ccode class=\"literal\"\u003eRETURNING\u003c/code\u003e clause in an SQL function does not return exactly the function's declared result type, \u003cspan class=\"productname\"\u003ePostgreSQL\u003c/span\u003e will automatically cast the value to the required type, if that is possible with an implicit or assignment cast. Otherwise, you must write an explicit cast. For example, suppose we wanted the previous \u003ccode class=\"function\"\u003eadd_em\u003c/code\u003e function to return type \u003ccode class=\"type\"\u003efloat8\u003c/code\u003e instead. It's sufficient to write\u003c/p\u003e\n\u003cpre class=\"programlisting\"\u003eCREATE FUNCTION add_em(integer, integer) RETURNS float8 AS $$\n    SELECT $1 + $2;\n$$ LANGUAGE SQL;\n\u003c/pre\u003e\n\u003cp\u003esince the \u003ccode class=\"type\"\u003einteger\u003c/code\u003e sum can be implicitly cast to \u003ccode class=\"type\"\u003efloat8\u003c/code\u003e. (See \u003ca class=\"xref\" href=\"/docs/18/typeconv.html\" title=\"Chapter 10. Type Conversion\"\u003eChapter 10\u003c/a\u003e or \u003ca class=\"xref\" href=\"/docs/18/sql-createcast.html\" title=\"CREATE CAST\"\u003e\u003cspan class=\"refentrytitle\"\u003eCREATE CAST\u003c/span\u003e\u003c/a\u003e for more about casts.)\u003c/p\u003e\n\u003c/div\u003e\n\u003cdiv class=\"sect2\" id=\"XFUNC-SQL-COMPOSITE-FUNCTIONS\"\u003e\n\u003cdiv class=\"titlepage\"\u003e\n\u003cdiv\u003e\n\u003cdiv\u003e\n\u003ch3 class=\"title\"\u003e36.5.3. SQL Functions on Composite Types \u003c/h3\u003e\n\u003c/div\u003e\n\u003c/div\u003e\n\u003c/div\u003e\n\u003cp\u003eWhen writing functions with arguments of composite types, we must not only specify which argument we want but also the desired attribute (field) of that argument. For example, suppose that \u003ccode class=\"type\"\u003eemp\u003c/code\u003e is a table containing employee data, and therefore also the name of the composite type of each row of the table. Here is a function \u003ccode class=\"function\"\u003edouble_salary\u003c/code\u003e that computes what someone's salary would be if it were doubled:\u003c/p\u003e\n\u003cpre class=\"screen\"\u003eCREATE TABLE emp (\n    name        text,\n    salary      numeric,\n    age         integer,\n    cubicle     point\n);\n\nINSERT INTO emp VALUES ('Bill', 4200, 45, '(2,1)');\n\nCREATE FUNCTION double_salary(emp) RETURNS numeric AS $$\n    SELECT $1.salary * 2 AS salary;\n$$ LANGUAGE SQL;\n\nSELECT name, double_salary(emp.*) AS dream\n    FROM emp\n    WHERE emp.cubicle ~= point '(2,1)';\n\n name | dream\n------+-------\n Bill |  8400\n\u003c/pre\u003e\n\u003cp\u003eNotice the use of the syntax \u003ccode class=\"literal\"\u003e$1.salary\u003c/code\u003e to select one field of the argument row value. Also notice how the calling \u003ccode class=\"command\"\u003eSELECT\u003c/code\u003e command uses \u003cem class=\"replaceable\"\u003e\u003ccode\u003etable_name\u003c/code\u003e\u003c/em\u003e\u003ccode class=\"literal\"\u003e.*\u003c/code\u003e to select the entire current row of a table as a composite value. The table row can alternatively be referenced using just the table name, like this:\u003c/p\u003e\n\u003cpre class=\"screen\"\u003eSELECT name, double_salary(emp) AS dream\n    FROM emp\n    WHERE emp.cubicle ~= point '(2,1)';\n\u003c/pre\u003e\n\u003cp\u003ebut this usage is deprecated since it's easy to get confused. (See \u003ca class=\"xref\" href=\"/docs/18/rowtypes.html#ROWTYPES-USAGE\" title=\"8.16.5. Using Composite Types in Queries\"\u003eSection 8.16.5\u003c/a\u003e for details about these two notations for the composite value of a table row.)\u003c/p\u003e\n\u003cp\u003eSometimes it is handy to construct a composite argument value on-the-fly. This can be done with the \u003ccode class=\"literal\"\u003eROW\u003c/code\u003e construct. For example, we could adjust the data being passed to the function:\u003c/p\u003e\n\u003cpre class=\"screen\"\u003eSELECT name, double_salary(ROW(name, salary*1.1, age, cubicle)) AS dream\n    FROM emp;\n\u003c/pre\u003e\n\u003cp\u003eIt is also possible to build a function that returns a composite type. This is an example of a function that returns a single \u003ccode class=\"type\"\u003eemp\u003c/code\u003e row:\u003c/p\u003e\n\u003cpre class=\"programlisting\"\u003eCREATE FUNCTION new_emp() RETURNS emp AS $$\n    SELECT text 'None' AS name,\n        1000.0 AS salary,\n        25 AS age,\n        point '(2,2)' AS cubicle;\n$$ LANGUAGE SQL;\n\u003c/pre\u003e\n\u003cp\u003eIn this example we have specified each of the attributes with a constant value, but any computation could have been substituted for these constants.\u003c/p\u003e\n\u003cp\u003eNote two important things about defining the function:\u003c/p\u003e\n\u003cdiv class=\"itemizedlist\"\u003e\n\u003cul class=\"itemizedlist\"\u003e\n\u003cli class=\"listitem\"\u003e\n\u003cp\u003eThe select list order in the query must be exactly the same as that in which the columns appear in the composite type. (Naming the columns, as we did above, is irrelevant to the system.)\u003c/p\u003e\n\u003c/li\u003e\n\u003cli class=\"listitem\"\u003e\n\u003cp\u003eWe must ensure each expression's type can be cast to that of the corresponding column of the composite type. Otherwise we'll get errors like this:\u003c/p\u003e\n\u003cpre class=\"screen\"\u003e\u003ccode class=\"computeroutput\"\u003e\nERROR:  return type mismatch in function declared to return emp\nDETAIL:  Final statement returns text instead of point at column 4.\n\u003c/code\u003e\n\u003c/pre\u003e\n\u003cp\u003eAs with the base-type case, the system will not insert explicit casts automatically, only implicit or assignment casts.\u003c/p\u003e\n\u003c/li\u003e\n\u003c/ul\u003e\n\u003c/div\u003e\n\u003cp\u003eA different way to define the same function is:\u003c/p\u003e\n\u003cpre class=\"programlisting\"\u003eCREATE FUNCTION new_emp() RETURNS emp AS $$\n    SELECT ROW('None', 1000.0, 25, '(2,2)')::emp;\n$$ LANGUAGE SQL;\n\u003c/pre\u003e\n\u003cp\u003eHere we wrote a \u003ccode class=\"command\"\u003eSELECT\u003c/code\u003e that returns just a single column of the correct composite type. This isn't really better in this situation, but it is a handy alternative in some cases — for example, if we need to compute the result by calling another function that returns the desired composite value. Another example is that if we are trying to write a function that returns a domain over composite, rather than a plain composite type, it is always necessary to write it as returning a single column, since there is no way to cause a coercion of the whole row result.\u003c/p\u003e\n\u003cp\u003eWe could call this function directly either by using it in a value expression:\u003c/p\u003e\n\u003cpre class=\"screen\"\u003eSELECT new_emp();\n\n         new_emp\n--------------------------\n (None,1000.0,25,\"(2,2)\")\n\u003c/pre\u003e\n\u003cp\u003eor by calling it as a table function:\u003c/p\u003e\n\u003cpre class=\"screen\"\u003eSELECT * FROM new_emp();\n\n name | salary | age | cubicle\n------+--------+-----+---------\n None | 1000.0 |  25 | (2,2)\n\u003c/pre\u003e\n\u003cp\u003eThe second way is described more fully in \u003ca class=\"xref\" href=\"/docs/18/xfunc-sql.html#XFUNC-SQL-TABLE-FUNCTIONS\" title=\"36.5.8. SQL Functions as Table Sources\"\u003eSection 36.5.8\u003c/a\u003e.\u003c/p\u003e\n\u003cp\u003eWhen you use a function that returns a composite type, you might want only one field (attribute) from its result. You can do that with syntax like this:\u003c/p\u003e\n\u003cpre class=\"screen\"\u003eSELECT (new_emp()).name;\n\n name\n------\n None\n\u003c/pre\u003e\n\u003cp\u003eThe extra parentheses are needed to keep the parser from getting confused. If you try to do it without them, you get something like this:\u003c/p\u003e\n\u003cpre class=\"screen\"\u003eSELECT new_emp().name;\nERROR:  syntax error at or near \".\"\nLINE 1: SELECT new_emp().name;\n                        ^\n\u003c/pre\u003e\n\u003cp\u003eAnother option is to use functional notation for extracting an attribute:\u003c/p\u003e\n\u003cpre class=\"screen\"\u003eSELECT name(new_emp());\n\n name\n------\n None\n\u003c/pre\u003e\n\u003cp\u003eAs explained in \u003ca class=\"xref\" href=\"/docs/18/rowtypes.html#ROWTYPES-USAGE\" title=\"8.16.5. Using Composite Types in Queries\"\u003eSection 8.16.5\u003c/a\u003e, the field notation and functional notation are equivalent.\u003c/p\u003e\n\u003cp\u003eAnother way to use a function returning a composite type is to pass the result to another function that accepts the correct row type as input:\u003c/p\u003e\n\u003cpre class=\"screen\"\u003eCREATE FUNCTION getname(emp) RETURNS text AS $$\n    SELECT $1.name;\n$$ LANGUAGE SQL;\n\nSELECT getname(new_emp());\n getname\n---------\n None\n(1 row)\n\u003c/pre\u003e\n\u003c/div\u003e\n\u003cdiv class=\"sect2\" id=\"XFUNC-OUTPUT-PARAMETERS\"\u003e\n\u003cdiv class=\"titlepage\"\u003e\n\u003cdiv\u003e\n\u003cdiv\u003e\n\u003ch3 class=\"title\"\u003e36.5.4. SQL Functions with Output Parameters \u003c/h3\u003e\n\u003c/div\u003e\n\u003c/div\u003e\n\u003c/div\u003e\n\u003cp\u003eAn alternative way of describing a function's results is to define it with \u003cem class=\"firstterm\"\u003eoutput parameters\u003c/em\u003e, as in this example:\u003c/p\u003e\n\u003cpre class=\"screen\"\u003eCREATE FUNCTION add_em (IN x int, IN y int, OUT sum int)\nAS 'SELECT x + y'\nLANGUAGE SQL;\n\nSELECT add_em(3,7);\n add_em\n--------\n     10\n(1 row)\n\u003c/pre\u003e\n\u003cp\u003eThis is not essentially different from the version of \u003ccode class=\"literal\"\u003eadd_em\u003c/code\u003e shown in \u003ca class=\"xref\" href=\"/docs/18/xfunc-sql.html#XFUNC-SQL-BASE-FUNCTIONS\" title=\"36.5.2. SQL Functions on Base Types\"\u003eSection 36.5.2\u003c/a\u003e. The real value of output parameters is that they provide a convenient way of defining functions that return several columns. For example,\u003c/p\u003e\n\u003cpre class=\"screen\"\u003eCREATE FUNCTION sum_n_product (x int, y int, OUT sum int, OUT product int)\nAS 'SELECT x + y, x * y'\nLANGUAGE SQL;\n\n SELECT * FROM sum_n_product(11,42);\n sum | product\n-----+---------\n  53 |     462\n(1 row)\n\u003c/pre\u003e\n\u003cp\u003eWhat has essentially happened here is that we have created an anonymous composite type for the result of the function. The above example has the same end result as\u003c/p\u003e\n\u003cpre class=\"screen\"\u003eCREATE TYPE sum_prod AS (sum int, product int);\n\nCREATE FUNCTION sum_n_product (int, int) RETURNS sum_prod\nAS 'SELECT $1 + $2, $1 * $2'\nLANGUAGE SQL;\n\u003c/pre\u003e\n\u003cp\u003ebut not having to bother with the separate composite type definition is often handy. Notice that the names attached to the output parameters are not just decoration, but determine the column names of the anonymous composite type. (If you omit a name for an output parameter, the system will choose a name on its own.)\u003c/p\u003e\n\u003cp\u003eNotice that output parameters are not included in the calling argument list when invoking such a function from SQL. This is because \u003cspan class=\"productname\"\u003ePostgreSQL\u003c/span\u003e considers only the input parameters to define the function's calling signature. That means also that only the input parameters matter when referencing the function for purposes such as dropping it. We could drop the above function with either of\u003c/p\u003e\n\u003cpre class=\"screen\"\u003eDROP FUNCTION sum_n_product (x int, y int, OUT sum int, OUT product int);\nDROP FUNCTION sum_n_product (int, int);\n\u003c/pre\u003e\n\u003cp\u003eParameters can be marked as \u003ccode class=\"literal\"\u003eIN\u003c/code\u003e (the default), \u003ccode class=\"literal\"\u003eOUT\u003c/code\u003e, \u003ccode class=\"literal\"\u003eINOUT\u003c/code\u003e, or \u003ccode class=\"literal\"\u003eVARIADIC\u003c/code\u003e. An \u003ccode class=\"literal\"\u003eINOUT\u003c/code\u003e parameter serves as both an input parameter (part of the calling argument list) and an output parameter (part of the result record type). \u003ccode class=\"literal\"\u003eVARIADIC\u003c/code\u003e parameters are input parameters, but are treated specially as described below.\u003c/p\u003e\n\u003c/div\u003e\n\u003cdiv class=\"sect2\" id=\"XFUNC-OUTPUT-PARAMETERS-PROC\"\u003e\n\u003cdiv class=\"titlepage\"\u003e\n\u003cdiv\u003e\n\u003cdiv\u003e\n\u003ch3 class=\"title\"\u003e36.5.5. SQL Procedures with Output Parameters \u003c/h3\u003e\n\u003c/div\u003e\n\u003c/div\u003e\n\u003c/div\u003e\n\u003cp\u003eOutput parameters are also supported in procedures, but they work a bit differently from functions. In \u003ccode class=\"command\"\u003eCALL\u003c/code\u003e commands, output parameters must be included in the argument list. For example, the bank account debiting routine from earlier could be written like this:\u003c/p\u003e\n\u003cpre class=\"programlisting\"\u003eCREATE PROCEDURE tp1 (accountno integer, debit numeric, OUT new_balance numeric) AS $$\n    UPDATE bank\n        SET balance = balance - debit\n        WHERE accountno = tp1.accountno\n    RETURNING balance;\n$$ LANGUAGE SQL;\n\u003c/pre\u003e\n\u003cp\u003eTo call this procedure, an argument matching the \u003ccode class=\"literal\"\u003eOUT\u003c/code\u003e parameter must be included. It's customary to write \u003ccode class=\"literal\"\u003eNULL\u003c/code\u003e:\u003c/p\u003e\n\u003cpre class=\"programlisting\"\u003eCALL tp1(17, 100.0, NULL);\n\u003c/pre\u003e\n\u003cp\u003eIf you write something else, it must be an expression that is implicitly coercible to the declared type of the parameter, just as for input parameters. Note however that such an expression will not be evaluated.\u003c/p\u003e\n\u003cp\u003eWhen calling a procedure from \u003cspan class=\"application\"\u003ePL/pgSQL\u003c/span\u003e, instead of writing \u003ccode class=\"literal\"\u003eNULL\u003c/code\u003e you must write a variable that will receive the procedure's output. See \u003ca class=\"xref\" href=\"/docs/18/plpgsql-control-structures.html#PLPGSQL-STATEMENTS-CALLING-PROCEDURE\" title=\"41.6.3. Calling a Procedure\"\u003eSection 41.6.3\u003c/a\u003e for details.\u003c/p\u003e\n\u003c/div\u003e\n\u003cdiv class=\"sect2\" id=\"XFUNC-SQL-VARIADIC-FUNCTIONS\"\u003e\n\u003cdiv class=\"titlepage\"\u003e\n\u003cdiv\u003e\n\u003cdiv\u003e\n\u003ch3 class=\"title\"\u003e36.5.6. SQL Functions with Variable Numbers of Arguments \u003c/h3\u003e\n\u003c/div\u003e\n\u003c/div\u003e\n\u003c/div\u003e\n\u003cp\u003eSQL functions can be declared to accept variable numbers of arguments, so long as all the \u003cspan class=\"quote\"\u003e“\u003cspan class=\"quote\"\u003eoptional\u003c/span\u003e”\u003c/span\u003e arguments are of the same data type. The optional arguments will be passed to the function as an array. The function is declared by marking the last parameter as \u003ccode class=\"literal\"\u003eVARIADIC\u003c/code\u003e; this parameter must be declared as being of an array type. For example:\u003c/p\u003e\n\u003cpre class=\"screen\"\u003eCREATE FUNCTION mleast(VARIADIC arr numeric[]) RETURNS numeric AS $$\n    SELECT min($1[i]) FROM generate_subscripts($1, 1) g(i);\n$$ LANGUAGE SQL;\n\nSELECT mleast(10, -1, 5, 4.4);\n mleast\n--------\n     -1\n(1 row)\n\u003c/pre\u003e\n\u003cp\u003eEffectively, all the actual arguments at or beyond the \u003ccode class=\"literal\"\u003eVARIADIC\u003c/code\u003e position are gathered up into a one-dimensional array, as if you had written\u003c/p\u003e\n\u003cpre class=\"screen\"\u003eSELECT mleast(ARRAY[10, -1, 5, 4.4]);    -- doesn't work\n\u003c/pre\u003e\n\u003cp\u003eYou can't actually write that, though — or at least, it will not match this function definition. A parameter marked \u003ccode class=\"literal\"\u003eVARIADIC\u003c/code\u003e matches one or more occurrences of its element type, not of its own type.\u003c/p\u003e\n\u003cp\u003eSometimes it is useful to be able to pass an already-constructed array to a variadic function; this is particularly handy when one variadic function wants to pass on its array parameter to another one. Also, this is the only secure way to call a variadic function found in a schema that permits untrusted users to create objects; see \u003ca class=\"xref\" href=\"/docs/18/typeconv-func.html\" title=\"10.3. Functions\"\u003eSection 10.3\u003c/a\u003e. You can do this by specifying \u003ccode class=\"literal\"\u003eVARIADIC\u003c/code\u003e in the call:\u003c/p\u003e\n\u003cpre class=\"screen\"\u003eSELECT mleast(VARIADIC ARRAY[10, -1, 5, 4.4]);\n\u003c/pre\u003e\n\u003cp\u003eThis prevents expansion of the function's variadic parameter into its element type, thereby allowing the array argument value to match normally. \u003ccode class=\"literal\"\u003eVARIADIC\u003c/code\u003e can only be attached to the last actual argument of a function call.\u003c/p\u003e\n\u003cp\u003eSpecifying \u003ccode class=\"literal\"\u003eVARIADIC\u003c/code\u003e in the call is also the only way to pass an empty array to a variadic function, for example:\u003c/p\u003e\n\u003cpre class=\"screen\"\u003eSELECT mleast(VARIADIC ARRAY[]::numeric[]);\n\u003c/pre\u003e\n\u003cp\u003eSimply writing \u003ccode class=\"literal\"\u003eSELECT mleast()\u003c/code\u003e does not work because a variadic parameter must match at least one actual argument. (You could define a second function also named \u003ccode class=\"literal\"\u003emleast\u003c/code\u003e, with no parameters, if you wanted to allow such calls.)\u003c/p\u003e\n\u003cp\u003eThe array element parameters generated from a variadic parameter are treated as not having any names of their own. This means it is not possible to call a variadic function using named arguments (\u003ca class=\"xref\" href=\"/docs/18/sql-syntax-calling-funcs.html\" title=\"4.3. Calling Functions\"\u003eSection 4.3\u003c/a\u003e), except when you specify \u003ccode class=\"literal\"\u003eVARIADIC\u003c/code\u003e. For example, this will work:\u003c/p\u003e\n\u003cpre class=\"screen\"\u003eSELECT mleast(VARIADIC arr =\u0026gt; ARRAY[10, -1, 5, 4.4]);\n\u003c/pre\u003e\n\u003cp\u003ebut not these:\u003c/p\u003e\n\u003cpre class=\"screen\"\u003eSELECT mleast(arr =\u0026gt; 10);\nSELECT mleast(arr =\u0026gt; ARRAY[10, -1, 5, 4.4]);\n\u003c/pre\u003e\n\u003c/div\u003e\n\u003cdiv class=\"sect2\" id=\"XFUNC-SQL-PARAMETER-DEFAULTS\"\u003e\n\u003cdiv class=\"titlepage\"\u003e\n\u003cdiv\u003e\n\u003cdiv\u003e\n\u003ch3 class=\"title\"\u003e36.5.7. SQL Functions with Default Values for Arguments \u003c/h3\u003e\n\u003c/div\u003e\n\u003c/div\u003e\n\u003c/div\u003e\n\u003cp\u003eFunctions can be declared with default values for some or all input arguments. The default values are inserted whenever the function is called with insufficiently many actual arguments. Since arguments can only be omitted from the end of the actual argument list, all parameters after a parameter with a default value have to have default values as well. (Although the use of named argument notation could allow this restriction to be relaxed, it's still enforced so that positional argument notation works sensibly.) Whether or not you use it, this capability creates a need for precautions when calling functions in databases where some users mistrust other users; see \u003ca class=\"xref\" href=\"/docs/18/typeconv-func.html\" title=\"10.3. Functions\"\u003eSection 10.3\u003c/a\u003e.\u003c/p\u003e\n\u003cp\u003eFor example:\u003c/p\u003e\n\u003cpre class=\"screen\"\u003eCREATE FUNCTION foo(a int, b int DEFAULT 2, c int DEFAULT 3)\nRETURNS int\nLANGUAGE SQL\nAS $$\n    SELECT $1 + $2 + $3;\n$$;\n\nSELECT foo(10, 20, 30);\n foo\n-----\n  60\n(1 row)\n\nSELECT foo(10, 20);\n foo\n-----\n  33\n(1 row)\n\nSELECT foo(10);\n foo\n-----\n  15\n(1 row)\n\nSELECT foo();  -- fails since there is no default for the first argument\nERROR:  function foo() does not exist\n\u003c/pre\u003e\n\u003cp\u003eThe \u003ccode class=\"literal\"\u003e=\u003c/code\u003e sign can also be used in place of the key word \u003ccode class=\"literal\"\u003eDEFAULT\u003c/code\u003e.\u003c/p\u003e\n\u003c/div\u003e\n\u003cdiv class=\"sect2\" id=\"XFUNC-SQL-TABLE-FUNCTIONS\"\u003e\n\u003cdiv class=\"titlepage\"\u003e\n\u003cdiv\u003e\n\u003cdiv\u003e\n\u003ch3 class=\"title\"\u003e36.5.8. SQL Functions as Table Sources \u003c/h3\u003e\n\u003c/div\u003e\n\u003c/div\u003e\n\u003c/div\u003e\n\u003cp\u003eAll SQL functions can be used in the \u003ccode class=\"literal\"\u003eFROM\u003c/code\u003e clause of a query, but it is particularly useful for functions returning composite types. If the function is defined to return a base type, the table function produces a one-column table. If the function is defined to return a composite type, the table function produces a column for each attribute of the composite type.\u003c/p\u003e\n\u003cp\u003eHere is an example:\u003c/p\u003e\n\u003cpre class=\"screen\"\u003eCREATE TABLE foo (fooid int, foosubid int, fooname text);\nINSERT INTO foo VALUES (1, 1, 'Joe');\nINSERT INTO foo VALUES (1, 2, 'Ed');\nINSERT INTO foo VALUES (2, 1, 'Mary');\n\nCREATE FUNCTION getfoo(int) RETURNS foo AS $$\n    SELECT * FROM foo WHERE fooid = $1;\n$$ LANGUAGE SQL;\n\nSELECT *, upper(fooname) FROM getfoo(1) AS t1;\n\n fooid | foosubid | fooname | upper\n-------+----------+---------+-------\n     1 |        1 | Joe     | JOE\n(1 row)\n\u003c/pre\u003e\n\u003cp\u003eAs the example shows, we can work with the columns of the function's result just the same as if they were columns of a regular table.\u003c/p\u003e\n\u003cp\u003eNote that we only got one row out of the function. This is because we did not use \u003ccode class=\"literal\"\u003eSETOF\u003c/code\u003e. That is described in the next section.\u003c/p\u003e\n\u003c/div\u003e\n\u003cdiv class=\"sect2\" id=\"XFUNC-SQL-FUNCTIONS-RETURNING-SET\"\u003e\n\u003cdiv class=\"titlepage\"\u003e\n\u003cdiv\u003e\n\u003cdiv\u003e\n\u003ch3 class=\"title\"\u003e36.5.9. SQL Functions Returning Sets \u003c/h3\u003e\n\u003c/div\u003e\n\u003c/div\u003e\n\u003c/div\u003e\n\u003cp\u003eWhen an SQL function is declared as returning \u003ccode class=\"literal\"\u003eSETOF \u003cem class=\"replaceable\"\u003e\u003ccode\u003esometype\u003c/code\u003e\u003c/em\u003e\u003c/code\u003e, the function's final query is executed to completion, and each row it outputs is returned as an element of the result set.\u003c/p\u003e\n\u003cp\u003eThis feature is normally used when calling the function in the \u003ccode class=\"literal\"\u003eFROM\u003c/code\u003e clause. In this case each row returned by the function becomes a row of the table seen by the query. For example, assume that table \u003ccode class=\"literal\"\u003efoo\u003c/code\u003e has the same contents as above, and we say:\u003c/p\u003e\n\u003cpre class=\"programlisting\"\u003eCREATE FUNCTION getfoo(int) RETURNS SETOF foo AS $$\n    SELECT * FROM foo WHERE fooid = $1;\n$$ LANGUAGE SQL;\n\nSELECT * FROM getfoo(1) AS t1;\n\u003c/pre\u003e\n\u003cp\u003eThen we would get:\u003c/p\u003e\n\u003cpre class=\"screen\"\u003e fooid | foosubid | fooname\n-------+----------+---------\n     1 |        1 | Joe\n     1 |        2 | Ed\n(2 rows)\n\u003c/pre\u003e\n\u003cp\u003eIt is also possible to return multiple rows with the columns defined by output parameters, like this:\u003c/p\u003e\n\u003cpre class=\"programlisting\"\u003eCREATE TABLE tab (y int, z int);\nINSERT INTO tab VALUES (1, 2), (3, 4), (5, 6), (7, 8);\n\nCREATE FUNCTION sum_n_product_with_tab (x int, OUT sum int, OUT product int)\nRETURNS SETOF record\nAS $$\n    SELECT $1 + tab.y, $1 * tab.y FROM tab;\n$$ LANGUAGE SQL;\n\nSELECT * FROM sum_n_product_with_tab(10);\n sum | product\n-----+---------\n  11 |      10\n  13 |      30\n  15 |      50\n  17 |      70\n(4 rows)\n\u003c/pre\u003e\n\u003cp\u003eThe key point here is that you must write \u003ccode class=\"literal\"\u003eRETURNS SETOF record\u003c/code\u003e to indicate that the function returns multiple rows instead of just one. If there is only one output parameter, write that parameter's type instead of \u003ccode class=\"type\"\u003erecord\u003c/code\u003e.\u003c/p\u003e\n\u003cp\u003eIt is frequently useful to construct a query's result by invoking a set-returning function multiple times, with the parameters for each invocation coming from successive rows of a table or subquery. The preferred way to do this is to use the \u003ccode class=\"literal\"\u003eLATERAL\u003c/code\u003e key word, which is described in \u003ca class=\"xref\" href=\"/docs/18/queries-table-expressions.html#QUERIES-LATERAL\" title=\"7.2.1.5. LATERAL Subqueries\"\u003eSection 7.2.1.5\u003c/a\u003e. Here is an example using a set-returning function to enumerate elements of a tree structure:\u003c/p\u003e\n\u003cpre class=\"screen\"\u003eSELECT * FROM nodes;\n   name    | parent\n-----------+--------\n Top       |\n Child1    | Top\n Child2    | Top\n Child3    | Top\n SubChild1 | Child1\n SubChild2 | Child1\n(6 rows)\n\nCREATE FUNCTION listchildren(text) RETURNS SETOF text AS $$\n    SELECT name FROM nodes WHERE parent = $1\n$$ LANGUAGE SQL STABLE;\n\nSELECT * FROM listchildren('Top');\n listchildren\n--------------\n Child1\n Child2\n Child3\n(3 rows)\n\nSELECT name, child FROM nodes, LATERAL listchildren(name) AS child;\n  name  |   child\n--------+-----------\n Top    | Child1\n Top    | Child2\n Top    | Child3\n Child1 | SubChild1\n Child1 | SubChild2\n(5 rows)\n\u003c/pre\u003e\n\u003cp\u003eThis example does not do anything that we couldn't have done with a simple join, but in more complex calculations the option to put some of the work into a function can be quite convenient.\u003c/p\u003e\n\u003cp\u003eFunctions returning sets can also be called in the select list of a query. For each row that the query generates by itself, the set-returning function is invoked, and an output row is generated for each element of the function's result set. The previous example could also be done with queries like these:\u003c/p\u003e\n\u003cpre class=\"screen\"\u003eSELECT listchildren('Top');\n listchildren\n--------------\n Child1\n Child2\n Child3\n(3 rows)\n\nSELECT name, listchildren(name) FROM nodes;\n  name  | listchildren\n--------+--------------\n Top    | Child1\n Top    | Child2\n Top    | Child3\n Child1 | SubChild1\n Child1 | SubChild2\n(5 rows)\n\u003c/pre\u003e\n\u003cp\u003eIn the last \u003ccode class=\"command\"\u003eSELECT\u003c/code\u003e, notice that no output row appears for \u003ccode class=\"literal\"\u003eChild2\u003c/code\u003e, \u003ccode class=\"literal\"\u003eChild3\u003c/code\u003e, etc. This happens because \u003ccode class=\"function\"\u003elistchildren\u003c/code\u003e returns an empty set for those arguments, so no result rows are generated. This is the same behavior as we got from an inner join to the function result when using the \u003ccode class=\"literal\"\u003eLATERAL\u003c/code\u003e syntax.\u003c/p\u003e\n\u003cp\u003e\u003cspan class=\"productname\"\u003ePostgreSQL\u003c/span\u003e's behavior for a set-returning function in a query's select list is almost exactly the same as if the set-returning function had been written in a \u003ccode class=\"literal\"\u003eLATERAL FROM\u003c/code\u003e-clause item instead. For example,\u003c/p\u003e\n\u003cpre class=\"programlisting\"\u003eSELECT x, generate_series(1,5) AS g FROM tab;\n\u003c/pre\u003e\n\u003cp\u003eis almost equivalent to\u003c/p\u003e\n\u003cpre class=\"programlisting\"\u003eSELECT x, g FROM tab, LATERAL generate_series(1,5) AS g;\n\u003c/pre\u003e\n\u003cp\u003eIt would be exactly the same, except that in this specific example, the planner could choose to put \u003ccode class=\"structname\"\u003eg\u003c/code\u003e on the outside of the nested-loop join, since \u003ccode class=\"structname\"\u003eg\u003c/code\u003e has no actual lateral dependency on \u003ccode class=\"structname\"\u003etab\u003c/code\u003e. That would result in a different output row order. Set-returning functions in the select list are always evaluated as though they are on the inside of a nested-loop join with the rest of the \u003ccode class=\"literal\"\u003eFROM\u003c/code\u003e clause, so that the function(s) are run to completion before the next row from the \u003ccode class=\"literal\"\u003eFROM\u003c/code\u003e clause is considered.\u003c/p\u003e\n\u003cp\u003eIf there is more than one set-returning function in the query's select list, the behavior is similar to what you get from putting the functions into a single \u003ccode class=\"literal\"\u003eLATERAL ROWS FROM( ... )\u003c/code\u003e \u003ccode class=\"literal\"\u003eFROM\u003c/code\u003e-clause item. For each row from the underlying query, there is an output row using the first result from each function, then an output row using the second result, and so on. If some of the set-returning functions produce fewer outputs than others, null values are substituted for the missing data, so that the total number of rows emitted for one underlying row is the same as for the set-returning function that produced the most outputs. Thus the set-returning functions run \u003cspan class=\"quote\"\u003e“\u003cspan class=\"quote\"\u003ein lockstep\u003c/span\u003e”\u003c/span\u003e until they are all exhausted, and then execution continues with the next underlying row.\u003c/p\u003e\n\u003cp\u003eSet-returning functions can be nested in a select list, although that is not allowed in \u003ccode class=\"literal\"\u003eFROM\u003c/code\u003e-clause items. In such cases, each level of nesting is treated separately, as though it were a separate \u003ccode class=\"literal\"\u003eLATERAL ROWS FROM( ... )\u003c/code\u003e item. For example, in\u003c/p\u003e\n\u003cpre class=\"programlisting\"\u003eSELECT srf1(srf2(x), srf3(y)), srf4(srf5(z)) FROM tab;\n\u003c/pre\u003e\n\u003cp\u003ethe set-returning functions \u003ccode class=\"function\"\u003esrf2\u003c/code\u003e, \u003ccode class=\"function\"\u003esrf3\u003c/code\u003e, and \u003ccode class=\"function\"\u003esrf5\u003c/code\u003e would be run in lockstep for each row of \u003ccode class=\"structname\"\u003etab\u003c/code\u003e, and then \u003ccode class=\"function\"\u003esrf1\u003c/code\u003e and \u003ccode class=\"function\"\u003esrf4\u003c/code\u003e would be applied in lockstep to each row produced by the lower functions.\u003c/p\u003e\n\u003cp\u003eSet-returning functions cannot be used within conditional-evaluation constructs, such as \u003ccode class=\"literal\"\u003eCASE\u003c/code\u003e or \u003ccode class=\"literal\"\u003eCOALESCE\u003c/code\u003e. For example, consider\u003c/p\u003e\n\u003cpre class=\"programlisting\"\u003eSELECT x, CASE WHEN x \u0026gt; 0 THEN generate_series(1, 5) ELSE 0 END FROM tab;\n\u003c/pre\u003e\n\u003cp\u003eIt might seem that this should produce five repetitions of input rows that have \u003ccode class=\"literal\"\u003ex \u0026gt; 0\u003c/code\u003e, and a single repetition of those that do not; but actually, because \u003ccode class=\"function\"\u003egenerate_series(1, 5)\u003c/code\u003e would be run in an implicit \u003ccode class=\"literal\"\u003eLATERAL FROM\u003c/code\u003e item before the \u003ccode class=\"literal\"\u003eCASE\u003c/code\u003e expression is ever evaluated, it would produce five repetitions of every input row. To reduce confusion, such cases produce a parse-time error instead.\u003c/p\u003e\n\u003cdiv class=\"note\"\u003e\n\u003ch3 class=\"title\"\u003eNote\u003c/h3\u003e\n\u003cp\u003eIf a function's last command is \u003ccode class=\"command\"\u003eINSERT\u003c/code\u003e, \u003ccode class=\"command\"\u003eUPDATE\u003c/code\u003e, \u003ccode class=\"command\"\u003eDELETE\u003c/code\u003e, or \u003ccode class=\"command\"\u003eMERGE\u003c/code\u003e with \u003ccode class=\"literal\"\u003eRETURNING\u003c/code\u003e, that command will always be executed to completion, even if the function is not declared with \u003ccode class=\"literal\"\u003eSETOF\u003c/code\u003e or the calling query does not fetch all the result rows. Any extra rows produced by the \u003ccode class=\"literal\"\u003eRETURNING\u003c/code\u003e clause are silently dropped, but the commanded table modifications still happen (and are all completed before returning from the function).\u003c/p\u003e\n\u003c/div\u003e\n\u003cdiv class=\"note\"\u003e\n\u003ch3 class=\"title\"\u003eNote\u003c/h3\u003e\n\u003cp\u003eBefore \u003cspan class=\"productname\"\u003ePostgreSQL\u003c/span\u003e 10, putting more than one set-returning function in the same select list did not behave very sensibly unless they always produced equal numbers of rows. Otherwise, what you got was a number of output rows equal to the least common multiple of the numbers of rows produced by the set-returning functions. Also, nested set-returning functions did not work as described above; instead, a set-returning function could have at most one set-returning argument, and each nest of set-returning functions was run independently. Also, conditional execution (set-returning functions inside \u003ccode class=\"literal\"\u003eCASE\u003c/code\u003e etc.) was previously allowed, complicating things even more. Use of the \u003ccode class=\"literal\"\u003eLATERAL\u003c/code\u003e syntax is recommended when writing queries that need to work in older \u003cspan class=\"productname\"\u003ePostgreSQL\u003c/span\u003e versions, because that will give consistent results across different versions. If you have a query that is relying on conditional execution of a set-returning function, you may be able to fix it by moving the conditional test into a custom set-returning function. For example,\u003c/p\u003e\n\u003cpre class=\"programlisting\"\u003eSELECT x, CASE WHEN y \u0026gt; 0 THEN generate_series(1, z) ELSE 5 END FROM tab;\n\u003c/pre\u003e\n\u003cp\u003ecould become\u003c/p\u003e\n\u003cpre class=\"programlisting\"\u003eCREATE FUNCTION case_generate_series(cond bool, start int, fin int, els int)\n  RETURNS SETOF int AS $$\nBEGIN\n  IF cond THEN\n    RETURN QUERY SELECT generate_series(start, fin);\n  ELSE\n    RETURN QUERY SELECT els;\n  END IF;\nEND$$ LANGUAGE plpgsql;\n\nSELECT x, case_generate_series(y \u0026gt; 0, 1, z, 5) FROM tab;\n\u003c/pre\u003e\n\u003cp\u003eThis formulation will work the same in all versions of \u003cspan class=\"productname\"\u003ePostgreSQL\u003c/span\u003e.\u003c/p\u003e\n\u003c/div\u003e\n\u003c/div\u003e\n\u003cdiv class=\"sect2\" id=\"XFUNC-SQL-FUNCTIONS-RETURNING-TABLE\"\u003e\n\u003cdiv class=\"titlepage\"\u003e\n\u003cdiv\u003e\n\u003cdiv\u003e\n\u003ch3 class=\"title\"\u003e36.5.10. SQL Functions Returning \u003ccode class=\"literal\"\u003eTABLE\u003c/code\u003e \u003c/h3\u003e\n\u003c/div\u003e\n\u003c/div\u003e\n\u003c/div\u003e\n\u003cp\u003eThere is another way to declare a function as returning a set, which is to use the syntax \u003ccode class=\"literal\"\u003eRETURNS TABLE(\u003cem class=\"replaceable\"\u003e\u003ccode\u003ecolumns\u003c/code\u003e\u003c/em\u003e)\u003c/code\u003e. This is equivalent to using one or more \u003ccode class=\"literal\"\u003eOUT\u003c/code\u003e parameters plus marking the function as returning \u003ccode class=\"literal\"\u003eSETOF record\u003c/code\u003e (or \u003ccode class=\"literal\"\u003eSETOF\u003c/code\u003e a single output parameter's type, as appropriate). This notation is specified in recent versions of the SQL standard, and thus may be more portable than using \u003ccode class=\"literal\"\u003eSETOF\u003c/code\u003e.\u003c/p\u003e\n\u003cp\u003eFor example, the preceding sum-and-product example could also be done this way:\u003c/p\u003e\n\u003cpre class=\"programlisting\"\u003eCREATE FUNCTION sum_n_product_with_tab (x int)\nRETURNS TABLE(sum int, product int) AS $$\n    SELECT $1 + tab.y, $1 * tab.y FROM tab;\n$$ LANGUAGE SQL;\n\u003c/pre\u003e\n\u003cp\u003eIt is not allowed to use explicit \u003ccode class=\"literal\"\u003eOUT\u003c/code\u003e or \u003ccode class=\"literal\"\u003eINOUT\u003c/code\u003e parameters with the \u003ccode class=\"literal\"\u003eRETURNS TABLE\u003c/code\u003e notation — you must put all the output columns in the \u003ccode class=\"literal\"\u003eTABLE\u003c/code\u003e list.\u003c/p\u003e\n\u003c/div\u003e\n\u003cdiv class=\"sect2\" id=\"XFUNC-SQL-POLYMORPHIC-FUNCTIONS\"\u003e\n\u003cdiv class=\"titlepage\"\u003e\n\u003cdiv\u003e\n\u003cdiv\u003e\n\u003ch3 class=\"title\"\u003e36.5.11. Polymorphic SQL Functions \u003c/h3\u003e\n\u003c/div\u003e\n\u003c/div\u003e\n\u003c/div\u003e\n\u003cp\u003eSQL functions can be declared to accept and return the polymorphic types described in \u003ca class=\"xref\" href=\"/docs/18/extend-type-system.html#EXTEND-TYPES-POLYMORPHIC\" title=\"36.2.5. Polymorphic Types\"\u003eSection 36.2.5\u003c/a\u003e. Here is a polymorphic function \u003ccode class=\"function\"\u003emake_array\u003c/code\u003e that builds up an array from two arbitrary data type elements:\u003c/p\u003e\n\u003cpre class=\"screen\"\u003eCREATE FUNCTION make_array(anyelement, anyelement) RETURNS anyarray AS $$\n    SELECT ARRAY[$1, $2];\n$$ LANGUAGE SQL;\n\nSELECT make_array(1, 2) AS intarray, make_array('a'::text, 'b') AS textarray;\n intarray | textarray\n----------+-----------\n {1,2}    | {a,b}\n(1 row)\n\u003c/pre\u003e\n\u003cp\u003eNotice the use of the typecast \u003ccode class=\"literal\"\u003e'a'::text\u003c/code\u003e to specify that the argument is of type \u003ccode class=\"type\"\u003etext\u003c/code\u003e. This is required if the argument is just a string literal, since otherwise it would be treated as type \u003ccode class=\"type\"\u003eunknown\u003c/code\u003e, and array of \u003ccode class=\"type\"\u003eunknown\u003c/code\u003e is not a valid type. Without the typecast, you will get errors like this:\u003c/p\u003e\n\u003cpre class=\"screen\"\u003eERROR:  could not determine polymorphic type because input has type unknown\n\u003c/pre\u003e\n\u003cp\u003eWith \u003ccode class=\"function\"\u003emake_array\u003c/code\u003e declared as above, you must provide two arguments that are of exactly the same data type; the system will not attempt to resolve any type differences. Thus for example this does not work:\u003c/p\u003e\n\u003cpre class=\"screen\"\u003eSELECT make_array(1, 2.5) AS numericarray;\nERROR:  function make_array(integer, numeric) does not exist\n\u003c/pre\u003e\n\u003cp\u003eAn alternative approach is to use the \u003cspan class=\"quote\"\u003e“\u003cspan class=\"quote\"\u003ecommon\u003c/span\u003e”\u003c/span\u003e family of polymorphic types, which allows the system to try to identify a suitable common type:\u003c/p\u003e\n\u003cpre class=\"screen\"\u003eCREATE FUNCTION make_array2(anycompatible, anycompatible)\nRETURNS anycompatiblearray AS $$\n    SELECT ARRAY[$1, $2];\n$$ LANGUAGE SQL;\n\nSELECT make_array2(1, 2.5) AS numericarray;\n numericarray\n--------------\n {1,2.5}\n(1 row)\n\u003c/pre\u003e\n\u003cp\u003eBecause the rules for common type resolution default to choosing type \u003ccode class=\"type\"\u003etext\u003c/code\u003e when all inputs are of unknown types, this also works:\u003c/p\u003e\n\u003cpre class=\"screen\"\u003eSELECT make_array2('a', 'b') AS textarray;\n textarray\n-----------\n {a,b}\n(1 row)\n\u003c/pre\u003e\n\u003cp\u003eIt is permitted to have polymorphic arguments with a fixed return type, but the converse is not. For example:\u003c/p\u003e\n\u003cpre class=\"screen\"\u003eCREATE FUNCTION is_greater(anyelement, anyelement) RETURNS boolean AS $$\n    SELECT $1 \u0026gt; $2;\n$$ LANGUAGE SQL;\n\nSELECT is_greater(1, 2);\n is_greater\n------------\n f\n(1 row)\n\nCREATE FUNCTION invalid_func() RETURNS anyelement AS $$\n    SELECT 1;\n$$ LANGUAGE SQL;\nERROR:  cannot determine result data type\nDETAIL:  A result of type anyelement requires at least one input of type anyelement, anyarray, anynonarray, anyenum, or anyrange.\n\u003c/pre\u003e\n\u003cp\u003ePolymorphism can be used with functions that have output arguments. For example:\u003c/p\u003e\n\u003cpre class=\"screen\"\u003eCREATE FUNCTION dup (f1 anyelement, OUT f2 anyelement, OUT f3 anyarray)\nAS 'select $1, array[$1,$1]' LANGUAGE SQL;\n\nSELECT * FROM dup(22);\n f2 |   f3\n----+---------\n 22 | {22,22}\n(1 row)\n\u003c/pre\u003e\n\u003cp\u003ePolymorphism can also be used with variadic functions. For example:\u003c/p\u003e\n\u003cpre class=\"screen\"\u003eCREATE FUNCTION anyleast (VARIADIC anyarray) RETURNS anyelement AS $$\n    SELECT min($1[i]) FROM generate_subscripts($1, 1) g(i);\n$$ LANGUAGE SQL;\n\nSELECT anyleast(10, -1, 5, 4);\n anyleast\n----------\n       -1\n(1 row)\n\nSELECT anyleast('abc'::text, 'def');\n anyleast\n----------\n abc\n(1 row)\n\nCREATE FUNCTION concat_values(text, VARIADIC anyarray) RETURNS text AS $$\n    SELECT array_to_string($2, $1);\n$$ LANGUAGE SQL;\n\nSELECT concat_values('|', 1, 4, 2);\n concat_values\n---------------\n 1|4|2\n(1 row)\n\u003c/pre\u003e\n\u003c/div\u003e\n\u003cdiv class=\"sect2\" id=\"XFUNC-SQL-COLLATIONS\"\u003e\n\u003cdiv class=\"titlepage\"\u003e\n\u003cdiv\u003e\n\u003cdiv\u003e\n\u003ch3 class=\"title\"\u003e36.5.12. SQL Functions with Collations \u003c/h3\u003e\n\u003c/div\u003e\n\u003c/div\u003e\n\u003c/div\u003e\n\u003cp\u003eWhen an SQL function has one or more parameters of collatable data types, a collation is identified for each function call depending on the collations assigned to the actual arguments, as described in \u003ca class=\"xref\" href=\"/docs/18/collation.html\" title=\"23.2. Collation Support\"\u003eSection 23.2\u003c/a\u003e. If a collation is successfully identified (i.e., there are no conflicts of implicit collations among the arguments) then all the collatable parameters are treated as having that collation implicitly. This will affect the behavior of collation-sensitive operations within the function. For example, using the \u003ccode class=\"function\"\u003eanyleast\u003c/code\u003e function described above, the result of\u003c/p\u003e\n\u003cpre class=\"programlisting\"\u003eSELECT anyleast('abc'::text, 'ABC');\n\u003c/pre\u003e\n\u003cp\u003ewill depend on the database's default collation. In \u003ccode class=\"literal\"\u003eC\u003c/code\u003e locale the result will be \u003ccode class=\"literal\"\u003eABC\u003c/code\u003e, but in many other locales it will be \u003ccode class=\"literal\"\u003eabc\u003c/code\u003e. The collation to use can be forced by adding a \u003ccode class=\"literal\"\u003eCOLLATE\u003c/code\u003e clause to any of the arguments, for example\u003c/p\u003e\n\u003cpre class=\"programlisting\"\u003eSELECT anyleast('abc'::text, 'ABC' COLLATE \"C\");\n\u003c/pre\u003e\n\u003cp\u003eAlternatively, if you wish a function to operate with a particular collation regardless of what it is called with, insert \u003ccode class=\"literal\"\u003eCOLLATE\u003c/code\u003e clauses as needed in the function definition. This version of \u003ccode class=\"function\"\u003eanyleast\u003c/code\u003e would always use \u003ccode class=\"literal\"\u003een_US\u003c/code\u003e locale to compare strings:\u003c/p\u003e\n\u003cpre class=\"programlisting\"\u003eCREATE FUNCTION anyleast (VARIADIC anyarray) RETURNS anyelement AS $$\n    SELECT min($1[i] COLLATE \"en_US\") FROM generate_subscripts($1, 1) g(i);\n$$ LANGUAGE SQL;\n\u003c/pre\u003e\n\u003cp\u003eBut note that this will throw an error if applied to a non-collatable data type.\u003c/p\u003e\n\u003cp\u003eIf no common collation can be identified among the actual arguments, then an SQL function treats its parameters as having their data types' default collation (which is usually the database's default collation, but could be different for parameters of domain types).\u003c/p\u003e\n\u003cp\u003eThe behavior of collatable parameters can be thought of as a limited form of polymorphism, applicable only to textual data types.\u003c/p\u003e\n\u003c/div\u003e\n\u003c/div\u003e","manual_path":"/docs/18/xfunc-sql.html","related":[],"release":{"catalog_fingerprint":"65c93d6048ef30e61023a84f9680fa6a92b1c383b7eb226741170077eb078502","channel":"stable","label":"18.6","major":"18","ref":"https://ftp.postgresql.org/pub/source/v18.6/postgresql-18.6.tar.bz2","revision":"555610c24d53e4316da5b7d3fc25c279d96856d5e0e23ee308c328c5fa881d9f","source_sha256":"555610c24d53e4316da5b7d3fc25c279d96856d5e0e23ee308c328c5fa881d9f"},"sections":[],"signature":"","sources":[{"label":"Matching PostgreSQL source archive","sha256":"555610c24d53e4316da5b7d3fc25c279d96856d5e0e23ee308c328c5fa881d9f","url":"https://ftp.postgresql.org/pub/source/v18.6/postgresql-18.6.tar.bz2"},{"label":"PostgreSQL 18 English manual","path":"xfunc-sql.html","sha256":"be6325441b9ed269d0566ef02c9e01bf4729ef7da9beef41463be00a7df3ad9c","url":"/docs/18/xfunc-sql.html"}],"tables":[]},"ManualEvidence":{"manual_path":"/docs/18/xfunc-sql.html","release":{"catalog_fingerprint":"65c93d6048ef30e61023a84f9680fa6a92b1c383b7eb226741170077eb078502","channel":"stable","label":"18.6","major":"18","ref":"https://ftp.postgresql.org/pub/source/v18.6/postgresql-18.6.tar.bz2","revision":"555610c24d53e4316da5b7d3fc25c279d96856d5e0e23ee308c328c5fa881d9f","source_sha256":"555610c24d53e4316da5b7d3fc25c279d96856d5e0e23ee308c328c5fa881d9f"},"sources":[{"label":"Matching PostgreSQL source archive","sha256":"555610c24d53e4316da5b7d3fc25c279d96856d5e0e23ee308c328c5fa881d9f","url":"https://ftp.postgresql.org/pub/source/v18.6/postgresql-18.6.tar.bz2"},{"label":"PostgreSQL 18 English manual","path":"xfunc-sql.html","sha256":"be6325441b9ed269d0566ef02c9e01bf4729ef7da9beef41463be00a7df3ad9c","url":"/docs/18/xfunc-sql.html"}]},"MeasuredEvidence":{}},"Text":{"Collection":"language","Key":"sql","SourceDatabase":"center","Version":"18","Locale":"en","Title":"sql","Summary":"SQL-language functions","BodyHTML":"\u003cdiv id=\"XFUNC-SQL\"\u003e\n\u003cdiv\u003e\n\u003cdiv\u003e\n\u003cdiv\u003e\n\u003ch2\u003e36.5. Query Language (SQL) Functions \u003c/h2\u003e\n\u003c/div\u003e\n\u003c/div\u003e\n\u003c/div\u003e\n\n\u003cp\u003eSQL functions execute an arbitrary list of SQL statements, returning the result of the last query in the list. In the simple (non-set) case, the first row of the last query\u0026#39;s result will be returned. (Bear in mind that \u003cspan\u003e“\u003cspan\u003ethe first row\u003c/span\u003e”\u003c/span\u003e of a multirow result is not well-defined unless you use \u003ccode\u003eORDER BY\u003c/code\u003e.) If the last query happens to return no rows at all, the null value will be returned.\u003c/p\u003e\n\u003cp\u003eAlternatively, an SQL function can be declared to return a set (that is, multiple rows) by specifying the function\u0026#39;s return type as \u003ccode\u003eSETOF \u003cem\u003e\u003ccode\u003esometype\u003c/code\u003e\u003c/em\u003e\u003c/code\u003e, or equivalently by declaring it as \u003ccode\u003eRETURNS TABLE(\u003cem\u003e\u003ccode\u003ecolumns\u003c/code\u003e\u003c/em\u003e)\u003c/code\u003e. In this case all rows of the last query\u0026#39;s result are returned. Further details appear below.\u003c/p\u003e\n\u003cp\u003eThe body of an SQL function must be a list of SQL statements separated by semicolons. A semicolon after the last statement is optional. Unless the function is declared to return \u003ccode\u003evoid\u003c/code\u003e, the last statement must be a \u003ccode\u003eSELECT\u003c/code\u003e, or an \u003ccode\u003eINSERT\u003c/code\u003e, \u003ccode\u003eUPDATE\u003c/code\u003e, \u003ccode\u003eDELETE\u003c/code\u003e, or \u003ccode\u003eMERGE\u003c/code\u003e that has a \u003ccode\u003eRETURNING\u003c/code\u003e clause.\u003c/p\u003e\n\u003cp\u003eAny collection of commands in the SQL language can be packaged together and defined as a function. Besides \u003ccode\u003eSELECT\u003c/code\u003e queries, the commands can include data modification queries (\u003ccode\u003eINSERT\u003c/code\u003e, \u003ccode\u003eUPDATE\u003c/code\u003e, \u003ccode\u003eDELETE\u003c/code\u003e, and \u003ccode\u003eMERGE\u003c/code\u003e), as well as other SQL commands. (You cannot use transaction control commands, e.g., \u003ccode\u003eCOMMIT\u003c/code\u003e, \u003ccode\u003eSAVEPOINT\u003c/code\u003e, and some utility commands, e.g., \u003ccode\u003eVACUUM\u003c/code\u003e, in SQL functions.) However, the final command must be a \u003ccode\u003eSELECT\u003c/code\u003e or have a \u003ccode\u003eRETURNING\u003c/code\u003e clause that returns whatever is specified as the function\u0026#39;s return type. Alternatively, if you want to define an SQL function that performs actions but has no useful value to return, you can define it as returning \u003ccode\u003evoid\u003c/code\u003e. For example, this function removes rows with negative salaries from the \u003ccode\u003eemp\u003c/code\u003e table:\u003c/p\u003e\n\u003cpre\u003eCREATE FUNCTION clean_emp() RETURNS void AS \u0026#39;\n    DELETE FROM emp\n        WHERE salary \u0026lt; 0;\n\u0026#39; LANGUAGE SQL;\n\nSELECT clean_emp();\n\n clean_emp\n-----------\n\n(1 row)\n\u003c/pre\u003e\n\u003cp\u003eYou can also write this as a procedure, thus avoiding the issue of the return type. For example:\u003c/p\u003e\n\u003cpre\u003eCREATE PROCEDURE clean_emp() AS \u0026#39;\n    DELETE FROM emp\n        WHERE salary \u0026lt; 0;\n\u0026#39; LANGUAGE SQL;\n\nCALL clean_emp();\n\u003c/pre\u003e\n\u003cp\u003eIn simple cases like this, the difference between a function returning \u003ccode\u003evoid\u003c/code\u003e and a procedure is mostly stylistic. However, procedures offer additional functionality such as transaction control that is not available in functions. Also, procedures are SQL standard whereas returning \u003ccode\u003evoid\u003c/code\u003e is a PostgreSQL extension.\u003c/p\u003e\n\u003cp\u003eThe syntax of the \u003ccode\u003eCREATE FUNCTION\u003c/code\u003e command requires the function body to be written as a string constant. It is usually most convenient to use dollar quoting (see \u003ca href=\"/docs/18/sql-syntax-lexical.html#SQL-SYNTAX-DOLLAR-QUOTING\" rel=\"nofollow\"\u003eSection 4.1.2.4\u003c/a\u003e) for the string constant. If you choose to use regular single-quoted string constant syntax, you must double single quote marks (\u003ccode\u003e\u0026#39;\u003c/code\u003e) and backslashes (\u003ccode\u003e\\\u003c/code\u003e) (assuming escape string syntax) in the body of the function (see \u003ca href=\"/docs/18/sql-syntax-lexical.html#SQL-SYNTAX-STRINGS\" rel=\"nofollow\"\u003eSection 4.1.2.1\u003c/a\u003e).\u003c/p\u003e\n\u003cdiv id=\"XFUNC-SQL-FUNCTION-ARGUMENTS\"\u003e\n\u003cdiv\u003e\n\u003cdiv\u003e\n\u003cdiv\u003e\n\u003ch3\u003e36.5.1. Arguments for SQL Functions \u003c/h3\u003e\n\u003c/div\u003e\n\u003c/div\u003e\n\u003c/div\u003e\n\u003cp\u003eArguments of an SQL function can be referenced in the function body using either names or numbers. Examples of both methods appear below.\u003c/p\u003e\n\u003cp\u003eTo use a name, declare the function argument as having a name, and then just write that name in the function body. If the argument name is the same as any column name in the current SQL command within the function, the column name will take precedence. To override this, qualify the argument name with the name of the function itself, that is \u003ccode\u003e\u003cem\u003e\u003ccode\u003efunction_name\u003c/code\u003e\u003c/em\u003e.\u003cem\u003e\u003ccode\u003eargument_name\u003c/code\u003e\u003c/em\u003e\u003c/code\u003e. (If this would conflict with a qualified column name, again the column name wins. You can avoid the ambiguity by choosing a different alias for the table within the SQL command.)\u003c/p\u003e\n\u003cp\u003eIn the older numeric approach, arguments are referenced using the syntax \u003ccode\u003e$\u003cem\u003e\u003ccode\u003en\u003c/code\u003e\u003c/em\u003e\u003c/code\u003e: \u003ccode\u003e$1\u003c/code\u003e refers to the first input argument, \u003ccode\u003e$2\u003c/code\u003e to the second, and so on. This will work whether or not the particular argument was declared with a name.\u003c/p\u003e\n\u003cp\u003eIf an argument is of a composite type, then the dot notation, e.g., \u003ccode\u003e\u003cem\u003e\u003ccode\u003eargname\u003c/code\u003e\u003c/em\u003e.\u003cem\u003e\u003ccode\u003efieldname\u003c/code\u003e\u003c/em\u003e\u003c/code\u003e or \u003ccode\u003e$1.\u003cem\u003e\u003ccode\u003efieldname\u003c/code\u003e\u003c/em\u003e\u003c/code\u003e, can be used to access attributes of the argument. Again, you might need to qualify the argument\u0026#39;s name with the function name to make the form with an argument name unambiguous.\u003c/p\u003e\n\u003cp\u003eSQL function arguments can only be used as data values, not as identifiers. Thus for example this is reasonable:\u003c/p\u003e\n\u003cpre\u003eINSERT INTO mytable VALUES ($1);\n\u003c/pre\u003e\n\u003cp\u003ebut this will not work:\u003c/p\u003e\n\u003cpre\u003eINSERT INTO $1 VALUES (42);\n\u003c/pre\u003e\n\u003cdiv\u003e\n\u003ch3\u003eNote\u003c/h3\u003e\n\u003cp\u003eThe ability to use names to reference SQL function arguments was added in \u003cspan\u003ePostgreSQL\u003c/span\u003e 9.2. Functions to be used in older servers must use the \u003ccode\u003e$\u003cem\u003e\u003ccode\u003en\u003c/code\u003e\u003c/em\u003e\u003c/code\u003e notation.\u003c/p\u003e\n\u003c/div\u003e\n\u003c/div\u003e\n\u003cdiv id=\"XFUNC-SQL-BASE-FUNCTIONS\"\u003e\n\u003cdiv\u003e\n\u003cdiv\u003e\n\u003cdiv\u003e\n\u003ch3\u003e36.5.2. SQL Functions on Base Types \u003c/h3\u003e\n\u003c/div\u003e\n\u003c/div\u003e\n\u003c/div\u003e\n\u003cp\u003eThe simplest possible SQL function has no arguments and simply returns a base type, such as \u003ccode\u003einteger\u003c/code\u003e:\u003c/p\u003e\n\u003cpre\u003eCREATE FUNCTION one() RETURNS integer AS $$\n    SELECT 1 AS result;\n$$ LANGUAGE SQL;\n\n-- Alternative syntax for string literal:\nCREATE FUNCTION one() RETURNS integer AS \u0026#39;\n    SELECT 1 AS result;\n\u0026#39; LANGUAGE SQL;\n\nSELECT one();\n\n one\n-----\n   1\n\u003c/pre\u003e\n\u003cp\u003eNotice that we defined a column alias within the function body for the result of the function (with the name \u003ccode\u003eresult\u003c/code\u003e), but this column alias is not visible outside the function. Hence, the result is labeled \u003ccode\u003eone\u003c/code\u003e instead of \u003ccode\u003eresult\u003c/code\u003e.\u003c/p\u003e\n\u003cp\u003eIt is almost as easy to define SQL functions that take base types as arguments:\u003c/p\u003e\n\u003cpre\u003eCREATE FUNCTION add_em(x integer, y integer) RETURNS integer AS $$\n    SELECT x + y;\n$$ LANGUAGE SQL;\n\nSELECT add_em(1, 2) AS answer;\n\n answer\n--------\n      3\n\u003c/pre\u003e\n\u003cp\u003eAlternatively, we could dispense with names for the arguments and use numbers:\u003c/p\u003e\n\u003cpre\u003eCREATE FUNCTION add_em(integer, integer) RETURNS integer AS $$\n    SELECT $1 + $2;\n$$ LANGUAGE SQL;\n\nSELECT add_em(1, 2) AS answer;\n\n answer\n--------\n      3\n\u003c/pre\u003e\n\u003cp\u003eHere is a more useful function, which might be used to debit a bank account:\u003c/p\u003e\n\u003cpre\u003eCREATE FUNCTION tf1 (accountno integer, debit numeric) RETURNS numeric AS $$\n    UPDATE bank\n        SET balance = balance - debit\n        WHERE accountno = tf1.accountno;\n    SELECT 1;\n$$ LANGUAGE SQL;\n\u003c/pre\u003e\n\u003cp\u003eA user could execute this function to debit account 17 by $100.00 as follows:\u003c/p\u003e\n\u003cpre\u003eSELECT tf1(17, 100.0);\n\u003c/pre\u003e\n\u003cp\u003eIn this example, we chose the name \u003ccode\u003eaccountno\u003c/code\u003e for the first argument, but this is the same as the name of a column in the \u003ccode\u003ebank\u003c/code\u003e table. Within the \u003ccode\u003eUPDATE\u003c/code\u003e command, \u003ccode\u003eaccountno\u003c/code\u003e refers to the column \u003ccode\u003ebank.accountno\u003c/code\u003e, so \u003ccode\u003etf1.accountno\u003c/code\u003e must be used to refer to the argument. We could of course avoid this by using a different name for the argument.\u003c/p\u003e\n\u003cp\u003eIn practice one would probably like a more useful result from the function than a constant 1, so a more likely definition is:\u003c/p\u003e\n\u003cpre\u003eCREATE FUNCTION tf1 (accountno integer, debit numeric) RETURNS numeric AS $$\n    UPDATE bank\n        SET balance = balance - debit\n        WHERE accountno = tf1.accountno;\n    SELECT balance FROM bank WHERE accountno = tf1.accountno;\n$$ LANGUAGE SQL;\n\u003c/pre\u003e\n\u003cp\u003ewhich adjusts the balance and returns the new balance. The same thing could be done in one command using \u003ccode\u003eRETURNING\u003c/code\u003e:\u003c/p\u003e\n\u003cpre\u003eCREATE FUNCTION tf1 (accountno integer, debit numeric) RETURNS numeric AS $$\n    UPDATE bank\n        SET balance = balance - debit\n        WHERE accountno = tf1.accountno\n    RETURNING balance;\n$$ LANGUAGE SQL;\n\u003c/pre\u003e\n\u003cp\u003eIf the final \u003ccode\u003eSELECT\u003c/code\u003e or \u003ccode\u003eRETURNING\u003c/code\u003e clause in an SQL function does not return exactly the function\u0026#39;s declared result type, \u003cspan\u003ePostgreSQL\u003c/span\u003e will automatically cast the value to the required type, if that is possible with an implicit or assignment cast. Otherwise, you must write an explicit cast. For example, suppose we wanted the previous \u003ccode\u003eadd_em\u003c/code\u003e function to return type \u003ccode\u003efloat8\u003c/code\u003e instead. It\u0026#39;s sufficient to write\u003c/p\u003e\n\u003cpre\u003eCREATE FUNCTION add_em(integer, integer) RETURNS float8 AS $$\n    SELECT $1 + $2;\n$$ LANGUAGE SQL;\n\u003c/pre\u003e\n\u003cp\u003esince the \u003ccode\u003einteger\u003c/code\u003e sum can be implicitly cast to \u003ccode\u003efloat8\u003c/code\u003e. (See \u003ca href=\"/docs/18/typeconv.html\" rel=\"nofollow\"\u003eChapter 10\u003c/a\u003e or \u003ca href=\"/docs/18/sql-createcast.html\" title=\"CREATE CAST\" rel=\"nofollow\"\u003e\u003cspan\u003eCREATE CAST\u003c/span\u003e\u003c/a\u003e for more about casts.)\u003c/p\u003e\n\u003c/div\u003e\n\u003cdiv id=\"XFUNC-SQL-COMPOSITE-FUNCTIONS\"\u003e\n\u003cdiv\u003e\n\u003cdiv\u003e\n\u003cdiv\u003e\n\u003ch3\u003e36.5.3. SQL Functions on Composite Types \u003c/h3\u003e\n\u003c/div\u003e\n\u003c/div\u003e\n\u003c/div\u003e\n\u003cp\u003eWhen writing functions with arguments of composite types, we must not only specify which argument we want but also the desired attribute (field) of that argument. For example, suppose that \u003ccode\u003eemp\u003c/code\u003e is a table containing employee data, and therefore also the name of the composite type of each row of the table. Here is a function \u003ccode\u003edouble_salary\u003c/code\u003e that computes what someone\u0026#39;s salary would be if it were doubled:\u003c/p\u003e\n\u003cpre\u003eCREATE TABLE emp (\n    name        text,\n    salary      numeric,\n    age         integer,\n    cubicle     point\n);\n\nINSERT INTO emp VALUES (\u0026#39;Bill\u0026#39;, 4200, 45, \u0026#39;(2,1)\u0026#39;);\n\nCREATE FUNCTION double_salary(emp) RETURNS numeric AS $$\n    SELECT $1.salary * 2 AS salary;\n$$ LANGUAGE SQL;\n\nSELECT name, double_salary(emp.*) AS dream\n    FROM emp\n    WHERE emp.cubicle ~= point \u0026#39;(2,1)\u0026#39;;\n\n name | dream\n------+-------\n Bill |  8400\n\u003c/pre\u003e\n\u003cp\u003eNotice the use of the syntax \u003ccode\u003e$1.salary\u003c/code\u003e to select one field of the argument row value. Also notice how the calling \u003ccode\u003eSELECT\u003c/code\u003e command uses \u003cem\u003e\u003ccode\u003etable_name\u003c/code\u003e\u003c/em\u003e\u003ccode\u003e.*\u003c/code\u003e to select the entire current row of a table as a composite value. The table row can alternatively be referenced using just the table name, like this:\u003c/p\u003e\n\u003cpre\u003eSELECT name, double_salary(emp) AS dream\n    FROM emp\n    WHERE emp.cubicle ~= point \u0026#39;(2,1)\u0026#39;;\n\u003c/pre\u003e\n\u003cp\u003ebut this usage is deprecated since it\u0026#39;s easy to get confused. (See \u003ca href=\"/docs/18/rowtypes.html#ROWTYPES-USAGE\" rel=\"nofollow\"\u003eSection 8.16.5\u003c/a\u003e for details about these two notations for the composite value of a table row.)\u003c/p\u003e\n\u003cp\u003eSometimes it is handy to construct a composite argument value on-the-fly. This can be done with the \u003ccode\u003eROW\u003c/code\u003e construct. For example, we could adjust the data being passed to the function:\u003c/p\u003e\n\u003cpre\u003eSELECT name, double_salary(ROW(name, salary*1.1, age, cubicle)) AS dream\n    FROM emp;\n\u003c/pre\u003e\n\u003cp\u003eIt is also possible to build a function that returns a composite type. This is an example of a function that returns a single \u003ccode\u003eemp\u003c/code\u003e row:\u003c/p\u003e\n\u003cpre\u003eCREATE FUNCTION new_emp() RETURNS emp AS $$\n    SELECT text \u0026#39;None\u0026#39; AS name,\n        1000.0 AS salary,\n        25 AS age,\n        point \u0026#39;(2,2)\u0026#39; AS cubicle;\n$$ LANGUAGE SQL;\n\u003c/pre\u003e\n\u003cp\u003eIn this example we have specified each of the attributes with a constant value, but any computation could have been substituted for these constants.\u003c/p\u003e\n\u003cp\u003eNote two important things about defining the function:\u003c/p\u003e\n\u003cdiv\u003e\n\u003cul\u003e\n\u003cli\u003e\n\u003cp\u003eThe select list order in the query must be exactly the same as that in which the columns appear in the composite type. (Naming the columns, as we did above, is irrelevant to the system.)\u003c/p\u003e\n\u003c/li\u003e\n\u003cli\u003e\n\u003cp\u003eWe must ensure each expression\u0026#39;s type can be cast to that of the corresponding column of the composite type. Otherwise we\u0026#39;ll get errors like this:\u003c/p\u003e\n\u003cpre\u003e\u003ccode\u003e\nERROR:  return type mismatch in function declared to return emp\nDETAIL:  Final statement returns text instead of point at column 4.\n\u003c/code\u003e\n\u003c/pre\u003e\n\u003cp\u003eAs with the base-type case, the system will not insert explicit casts automatically, only implicit or assignment casts.\u003c/p\u003e\n\u003c/li\u003e\n\u003c/ul\u003e\n\u003c/div\u003e\n\u003cp\u003eA different way to define the same function is:\u003c/p\u003e\n\u003cpre\u003eCREATE FUNCTION new_emp() RETURNS emp AS $$\n    SELECT ROW(\u0026#39;None\u0026#39;, 1000.0, 25, \u0026#39;(2,2)\u0026#39;)::emp;\n$$ LANGUAGE SQL;\n\u003c/pre\u003e\n\u003cp\u003eHere we wrote a \u003ccode\u003eSELECT\u003c/code\u003e that returns just a single column of the correct composite type. This isn\u0026#39;t really better in this situation, but it is a handy alternative in some cases — for example, if we need to compute the result by calling another function that returns the desired composite value. Another example is that if we are trying to write a function that returns a domain over composite, rather than a plain composite type, it is always necessary to write it as returning a single column, since there is no way to cause a coercion of the whole row result.\u003c/p\u003e\n\u003cp\u003eWe could call this function directly either by using it in a value expression:\u003c/p\u003e\n\u003cpre\u003eSELECT new_emp();\n\n         new_emp\n--------------------------\n (None,1000.0,25,\u0026#34;(2,2)\u0026#34;)\n\u003c/pre\u003e\n\u003cp\u003eor by calling it as a table function:\u003c/p\u003e\n\u003cpre\u003eSELECT * FROM new_emp();\n\n name | salary | age | cubicle\n------+--------+-----+---------\n None | 1000.0 |  25 | (2,2)\n\u003c/pre\u003e\n\u003cp\u003eThe second way is described more fully in \u003ca href=\"/docs/18/xfunc-sql.html#XFUNC-SQL-TABLE-FUNCTIONS\" rel=\"nofollow\"\u003eSection 36.5.8\u003c/a\u003e.\u003c/p\u003e\n\u003cp\u003eWhen you use a function that returns a composite type, you might want only one field (attribute) from its result. You can do that with syntax like this:\u003c/p\u003e\n\u003cpre\u003eSELECT (new_emp()).name;\n\n name\n------\n None\n\u003c/pre\u003e\n\u003cp\u003eThe extra parentheses are needed to keep the parser from getting confused. If you try to do it without them, you get something like this:\u003c/p\u003e\n\u003cpre\u003eSELECT new_emp().name;\nERROR:  syntax error at or near \u0026#34;.\u0026#34;\nLINE 1: SELECT new_emp().name;\n                        ^\n\u003c/pre\u003e\n\u003cp\u003eAnother option is to use functional notation for extracting an attribute:\u003c/p\u003e\n\u003cpre\u003eSELECT name(new_emp());\n\n name\n------\n None\n\u003c/pre\u003e\n\u003cp\u003eAs explained in \u003ca href=\"/docs/18/rowtypes.html#ROWTYPES-USAGE\" rel=\"nofollow\"\u003eSection 8.16.5\u003c/a\u003e, the field notation and functional notation are equivalent.\u003c/p\u003e\n\u003cp\u003eAnother way to use a function returning a composite type is to pass the result to another function that accepts the correct row type as input:\u003c/p\u003e\n\u003cpre\u003eCREATE FUNCTION getname(emp) RETURNS text AS $$\n    SELECT $1.name;\n$$ LANGUAGE SQL;\n\nSELECT getname(new_emp());\n getname\n---------\n None\n(1 row)\n\u003c/pre\u003e\n\u003c/div\u003e\n\u003cdiv id=\"XFUNC-OUTPUT-PARAMETERS\"\u003e\n\u003cdiv\u003e\n\u003cdiv\u003e\n\u003cdiv\u003e\n\u003ch3\u003e36.5.4. SQL Functions with Output Parameters \u003c/h3\u003e\n\u003c/div\u003e\n\u003c/div\u003e\n\u003c/div\u003e\n\u003cp\u003eAn alternative way of describing a function\u0026#39;s results is to define it with \u003cem\u003eoutput parameters\u003c/em\u003e, as in this example:\u003c/p\u003e\n\u003cpre\u003eCREATE FUNCTION add_em (IN x int, IN y int, OUT sum int)\nAS \u0026#39;SELECT x + y\u0026#39;\nLANGUAGE SQL;\n\nSELECT add_em(3,7);\n add_em\n--------\n     10\n(1 row)\n\u003c/pre\u003e\n\u003cp\u003eThis is not essentially different from the version of \u003ccode\u003eadd_em\u003c/code\u003e shown in \u003ca href=\"/docs/18/xfunc-sql.html#XFUNC-SQL-BASE-FUNCTIONS\" rel=\"nofollow\"\u003eSection 36.5.2\u003c/a\u003e. The real value of output parameters is that they provide a convenient way of defining functions that return several columns. For example,\u003c/p\u003e\n\u003cpre\u003eCREATE FUNCTION sum_n_product (x int, y int, OUT sum int, OUT product int)\nAS \u0026#39;SELECT x + y, x * y\u0026#39;\nLANGUAGE SQL;\n\n SELECT * FROM sum_n_product(11,42);\n sum | product\n-----+---------\n  53 |     462\n(1 row)\n\u003c/pre\u003e\n\u003cp\u003eWhat has essentially happened here is that we have created an anonymous composite type for the result of the function. The above example has the same end result as\u003c/p\u003e\n\u003cpre\u003eCREATE TYPE sum_prod AS (sum int, product int);\n\nCREATE FUNCTION sum_n_product (int, int) RETURNS sum_prod\nAS \u0026#39;SELECT $1 + $2, $1 * $2\u0026#39;\nLANGUAGE SQL;\n\u003c/pre\u003e\n\u003cp\u003ebut not having to bother with the separate composite type definition is often handy. Notice that the names attached to the output parameters are not just decoration, but determine the column names of the anonymous composite type. (If you omit a name for an output parameter, the system will choose a name on its own.)\u003c/p\u003e\n\u003cp\u003eNotice that output parameters are not included in the calling argument list when invoking such a function from SQL. This is because \u003cspan\u003ePostgreSQL\u003c/span\u003e considers only the input parameters to define the function\u0026#39;s calling signature. That means also that only the input parameters matter when referencing the function for purposes such as dropping it. We could drop the above function with either of\u003c/p\u003e\n\u003cpre\u003eDROP FUNCTION sum_n_product (x int, y int, OUT sum int, OUT product int);\nDROP FUNCTION sum_n_product (int, int);\n\u003c/pre\u003e\n\u003cp\u003eParameters can be marked as \u003ccode\u003eIN\u003c/code\u003e (the default), \u003ccode\u003eOUT\u003c/code\u003e, \u003ccode\u003eINOUT\u003c/code\u003e, or \u003ccode\u003eVARIADIC\u003c/code\u003e. An \u003ccode\u003eINOUT\u003c/code\u003e parameter serves as both an input parameter (part of the calling argument list) and an output parameter (part of the result record type). \u003ccode\u003eVARIADIC\u003c/code\u003e parameters are input parameters, but are treated specially as described below.\u003c/p\u003e\n\u003c/div\u003e\n\u003cdiv id=\"XFUNC-OUTPUT-PARAMETERS-PROC\"\u003e\n\u003cdiv\u003e\n\u003cdiv\u003e\n\u003cdiv\u003e\n\u003ch3\u003e36.5.5. SQL Procedures with Output Parameters \u003c/h3\u003e\n\u003c/div\u003e\n\u003c/div\u003e\n\u003c/div\u003e\n\u003cp\u003eOutput parameters are also supported in procedures, but they work a bit differently from functions. In \u003ccode\u003eCALL\u003c/code\u003e commands, output parameters must be included in the argument list. For example, the bank account debiting routine from earlier could be written like this:\u003c/p\u003e\n\u003cpre\u003eCREATE PROCEDURE tp1 (accountno integer, debit numeric, OUT new_balance numeric) AS $$\n    UPDATE bank\n        SET balance = balance - debit\n        WHERE accountno = tp1.accountno\n    RETURNING balance;\n$$ LANGUAGE SQL;\n\u003c/pre\u003e\n\u003cp\u003eTo call this procedure, an argument matching the \u003ccode\u003eOUT\u003c/code\u003e parameter must be included. It\u0026#39;s customary to write \u003ccode\u003eNULL\u003c/code\u003e:\u003c/p\u003e\n\u003cpre\u003eCALL tp1(17, 100.0, NULL);\n\u003c/pre\u003e\n\u003cp\u003eIf you write something else, it must be an expression that is implicitly coercible to the declared type of the parameter, just as for input parameters. Note however that such an expression will not be evaluated.\u003c/p\u003e\n\u003cp\u003eWhen calling a procedure from \u003cspan\u003ePL/pgSQL\u003c/span\u003e, instead of writing \u003ccode\u003eNULL\u003c/code\u003e you must write a variable that will receive the procedure\u0026#39;s output. See \u003ca href=\"/docs/18/plpgsql-control-structures.html#PLPGSQL-STATEMENTS-CALLING-PROCEDURE\" rel=\"nofollow\"\u003eSection 41.6.3\u003c/a\u003e for details.\u003c/p\u003e\n\u003c/div\u003e\n\u003cdiv id=\"XFUNC-SQL-VARIADIC-FUNCTIONS\"\u003e\n\u003cdiv\u003e\n\u003cdiv\u003e\n\u003cdiv\u003e\n\u003ch3\u003e36.5.6. SQL Functions with Variable Numbers of Arguments \u003c/h3\u003e\n\u003c/div\u003e\n\u003c/div\u003e\n\u003c/div\u003e\n\u003cp\u003eSQL functions can be declared to accept variable numbers of arguments, so long as all the \u003cspan\u003e“\u003cspan\u003eoptional\u003c/span\u003e”\u003c/span\u003e arguments are of the same data type. The optional arguments will be passed to the function as an array. The function is declared by marking the last parameter as \u003ccode\u003eVARIADIC\u003c/code\u003e; this parameter must be declared as being of an array type. For example:\u003c/p\u003e\n\u003cpre\u003eCREATE FUNCTION mleast(VARIADIC arr numeric[]) RETURNS numeric AS $$\n    SELECT min($1[i]) FROM generate_subscripts($1, 1) g(i);\n$$ LANGUAGE SQL;\n\nSELECT mleast(10, -1, 5, 4.4);\n mleast\n--------\n     -1\n(1 row)\n\u003c/pre\u003e\n\u003cp\u003eEffectively, all the actual arguments at or beyond the \u003ccode\u003eVARIADIC\u003c/code\u003e position are gathered up into a one-dimensional array, as if you had written\u003c/p\u003e\n\u003cpre\u003eSELECT mleast(ARRAY[10, -1, 5, 4.4]);    -- doesn\u0026#39;t work\n\u003c/pre\u003e\n\u003cp\u003eYou can\u0026#39;t actually write that, though — or at least, it will not match this function definition. A parameter marked \u003ccode\u003eVARIADIC\u003c/code\u003e matches one or more occurrences of its element type, not of its own type.\u003c/p\u003e\n\u003cp\u003eSometimes it is useful to be able to pass an already-constructed array to a variadic function; this is particularly handy when one variadic function wants to pass on its array parameter to another one. Also, this is the only secure way to call a variadic function found in a schema that permits untrusted users to create objects; see \u003ca href=\"/docs/18/typeconv-func.html\" rel=\"nofollow\"\u003eSection 10.3\u003c/a\u003e. You can do this by specifying \u003ccode\u003eVARIADIC\u003c/code\u003e in the call:\u003c/p\u003e\n\u003cpre\u003eSELECT mleast(VARIADIC ARRAY[10, -1, 5, 4.4]);\n\u003c/pre\u003e\n\u003cp\u003eThis prevents expansion of the function\u0026#39;s variadic parameter into its element type, thereby allowing the array argument value to match normally. \u003ccode\u003eVARIADIC\u003c/code\u003e can only be attached to the last actual argument of a function call.\u003c/p\u003e\n\u003cp\u003eSpecifying \u003ccode\u003eVARIADIC\u003c/code\u003e in the call is also the only way to pass an empty array to a variadic function, for example:\u003c/p\u003e\n\u003cpre\u003eSELECT mleast(VARIADIC ARRAY[]::numeric[]);\n\u003c/pre\u003e\n\u003cp\u003eSimply writing \u003ccode\u003eSELECT mleast()\u003c/code\u003e does not work because a variadic parameter must match at least one actual argument. (You could define a second function also named \u003ccode\u003emleast\u003c/code\u003e, with no parameters, if you wanted to allow such calls.)\u003c/p\u003e\n\u003cp\u003eThe array element parameters generated from a variadic parameter are treated as not having any names of their own. This means it is not possible to call a variadic function using named arguments (\u003ca href=\"/docs/18/sql-syntax-calling-funcs.html\" rel=\"nofollow\"\u003eSection 4.3\u003c/a\u003e), except when you specify \u003ccode\u003eVARIADIC\u003c/code\u003e. For example, this will work:\u003c/p\u003e\n\u003cpre\u003eSELECT mleast(VARIADIC arr =\u0026gt; ARRAY[10, -1, 5, 4.4]);\n\u003c/pre\u003e\n\u003cp\u003ebut not these:\u003c/p\u003e\n\u003cpre\u003eSELECT mleast(arr =\u0026gt; 10);\nSELECT mleast(arr =\u0026gt; ARRAY[10, -1, 5, 4.4]);\n\u003c/pre\u003e\n\u003c/div\u003e\n\u003cdiv id=\"XFUNC-SQL-PARAMETER-DEFAULTS\"\u003e\n\u003cdiv\u003e\n\u003cdiv\u003e\n\u003cdiv\u003e\n\u003ch3\u003e36.5.7. SQL Functions with Default Values for Arguments \u003c/h3\u003e\n\u003c/div\u003e\n\u003c/div\u003e\n\u003c/div\u003e\n\u003cp\u003eFunctions can be declared with default values for some or all input arguments. The default values are inserted whenever the function is called with insufficiently many actual arguments. Since arguments can only be omitted from the end of the actual argument list, all parameters after a parameter with a default value have to have default values as well. (Although the use of named argument notation could allow this restriction to be relaxed, it\u0026#39;s still enforced so that positional argument notation works sensibly.) Whether or not you use it, this capability creates a need for precautions when calling functions in databases where some users mistrust other users; see \u003ca href=\"/docs/18/typeconv-func.html\" rel=\"nofollow\"\u003eSection 10.3\u003c/a\u003e.\u003c/p\u003e\n\u003cp\u003eFor example:\u003c/p\u003e\n\u003cpre\u003eCREATE FUNCTION foo(a int, b int DEFAULT 2, c int DEFAULT 3)\nRETURNS int\nLANGUAGE SQL\nAS $$\n    SELECT $1 + $2 + $3;\n$$;\n\nSELECT foo(10, 20, 30);\n foo\n-----\n  60\n(1 row)\n\nSELECT foo(10, 20);\n foo\n-----\n  33\n(1 row)\n\nSELECT foo(10);\n foo\n-----\n  15\n(1 row)\n\nSELECT foo();  -- fails since there is no default for the first argument\nERROR:  function foo() does not exist\n\u003c/pre\u003e\n\u003cp\u003eThe \u003ccode\u003e=\u003c/code\u003e sign can also be used in place of the key word \u003ccode\u003eDEFAULT\u003c/code\u003e.\u003c/p\u003e\n\u003c/div\u003e\n\u003cdiv id=\"XFUNC-SQL-TABLE-FUNCTIONS\"\u003e\n\u003cdiv\u003e\n\u003cdiv\u003e\n\u003cdiv\u003e\n\u003ch3\u003e36.5.8. SQL Functions as Table Sources \u003c/h3\u003e\n\u003c/div\u003e\n\u003c/div\u003e\n\u003c/div\u003e\n\u003cp\u003eAll SQL functions can be used in the \u003ccode\u003eFROM\u003c/code\u003e clause of a query, but it is particularly useful for functions returning composite types. If the function is defined to return a base type, the table function produces a one-column table. If the function is defined to return a composite type, the table function produces a column for each attribute of the composite type.\u003c/p\u003e\n\u003cp\u003eHere is an example:\u003c/p\u003e\n\u003cpre\u003eCREATE TABLE foo (fooid int, foosubid int, fooname text);\nINSERT INTO foo VALUES (1, 1, \u0026#39;Joe\u0026#39;);\nINSERT INTO foo VALUES (1, 2, \u0026#39;Ed\u0026#39;);\nINSERT INTO foo VALUES (2, 1, \u0026#39;Mary\u0026#39;);\n\nCREATE FUNCTION getfoo(int) RETURNS foo AS $$\n    SELECT * FROM foo WHERE fooid = $1;\n$$ LANGUAGE SQL;\n\nSELECT *, upper(fooname) FROM getfoo(1) AS t1;\n\n fooid | foosubid | fooname | upper\n-------+----------+---------+-------\n     1 |        1 | Joe     | JOE\n(1 row)\n\u003c/pre\u003e\n\u003cp\u003eAs the example shows, we can work with the columns of the function\u0026#39;s result just the same as if they were columns of a regular table.\u003c/p\u003e\n\u003cp\u003eNote that we only got one row out of the function. This is because we did not use \u003ccode\u003eSETOF\u003c/code\u003e. That is described in the next section.\u003c/p\u003e\n\u003c/div\u003e\n\u003cdiv id=\"XFUNC-SQL-FUNCTIONS-RETURNING-SET\"\u003e\n\u003cdiv\u003e\n\u003cdiv\u003e\n\u003cdiv\u003e\n\u003ch3\u003e36.5.9. SQL Functions Returning Sets \u003c/h3\u003e\n\u003c/div\u003e\n\u003c/div\u003e\n\u003c/div\u003e\n\u003cp\u003eWhen an SQL function is declared as returning \u003ccode\u003eSETOF \u003cem\u003e\u003ccode\u003esometype\u003c/code\u003e\u003c/em\u003e\u003c/code\u003e, the function\u0026#39;s final query is executed to completion, and each row it outputs is returned as an element of the result set.\u003c/p\u003e\n\u003cp\u003eThis feature is normally used when calling the function in the \u003ccode\u003eFROM\u003c/code\u003e clause. In this case each row returned by the function becomes a row of the table seen by the query. For example, assume that table \u003ccode\u003efoo\u003c/code\u003e has the same contents as above, and we say:\u003c/p\u003e\n\u003cpre\u003eCREATE FUNCTION getfoo(int) RETURNS SETOF foo AS $$\n    SELECT * FROM foo WHERE fooid = $1;\n$$ LANGUAGE SQL;\n\nSELECT * FROM getfoo(1) AS t1;\n\u003c/pre\u003e\n\u003cp\u003eThen we would get:\u003c/p\u003e\n\u003cpre\u003e fooid | foosubid | fooname\n-------+----------+---------\n     1 |        1 | Joe\n     1 |        2 | Ed\n(2 rows)\n\u003c/pre\u003e\n\u003cp\u003eIt is also possible to return multiple rows with the columns defined by output parameters, like this:\u003c/p\u003e\n\u003cpre\u003eCREATE TABLE tab (y int, z int);\nINSERT INTO tab VALUES (1, 2), (3, 4), (5, 6), (7, 8);\n\nCREATE FUNCTION sum_n_product_with_tab (x int, OUT sum int, OUT product int)\nRETURNS SETOF record\nAS $$\n    SELECT $1 + tab.y, $1 * tab.y FROM tab;\n$$ LANGUAGE SQL;\n\nSELECT * FROM sum_n_product_with_tab(10);\n sum | product\n-----+---------\n  11 |      10\n  13 |      30\n  15 |      50\n  17 |      70\n(4 rows)\n\u003c/pre\u003e\n\u003cp\u003eThe key point here is that you must write \u003ccode\u003eRETURNS SETOF record\u003c/code\u003e to indicate that the function returns multiple rows instead of just one. If there is only one output parameter, write that parameter\u0026#39;s type instead of \u003ccode\u003erecord\u003c/code\u003e.\u003c/p\u003e\n\u003cp\u003eIt is frequently useful to construct a query\u0026#39;s result by invoking a set-returning function multiple times, with the parameters for each invocation coming from successive rows of a table or subquery. The preferred way to do this is to use the \u003ccode\u003eLATERAL\u003c/code\u003e key word, which is described in \u003ca href=\"/docs/18/queries-table-expressions.html#QUERIES-LATERAL\" rel=\"nofollow\"\u003eSection 7.2.1.5\u003c/a\u003e. Here is an example using a set-returning function to enumerate elements of a tree structure:\u003c/p\u003e\n\u003cpre\u003eSELECT * FROM nodes;\n   name    | parent\n-----------+--------\n Top       |\n Child1    | Top\n Child2    | Top\n Child3    | Top\n SubChild1 | Child1\n SubChild2 | Child1\n(6 rows)\n\nCREATE FUNCTION listchildren(text) RETURNS SETOF text AS $$\n    SELECT name FROM nodes WHERE parent = $1\n$$ LANGUAGE SQL STABLE;\n\nSELECT * FROM listchildren(\u0026#39;Top\u0026#39;);\n listchildren\n--------------\n Child1\n Child2\n Child3\n(3 rows)\n\nSELECT name, child FROM nodes, LATERAL listchildren(name) AS child;\n  name  |   child\n--------+-----------\n Top    | Child1\n Top    | Child2\n Top    | Child3\n Child1 | SubChild1\n Child1 | SubChild2\n(5 rows)\n\u003c/pre\u003e\n\u003cp\u003eThis example does not do anything that we couldn\u0026#39;t have done with a simple join, but in more complex calculations the option to put some of the work into a function can be quite convenient.\u003c/p\u003e\n\u003cp\u003eFunctions returning sets can also be called in the select list of a query. For each row that the query generates by itself, the set-returning function is invoked, and an output row is generated for each element of the function\u0026#39;s result set. The previous example could also be done with queries like these:\u003c/p\u003e\n\u003cpre\u003eSELECT listchildren(\u0026#39;Top\u0026#39;);\n listchildren\n--------------\n Child1\n Child2\n Child3\n(3 rows)\n\nSELECT name, listchildren(name) FROM nodes;\n  name  | listchildren\n--------+--------------\n Top    | Child1\n Top    | Child2\n Top    | Child3\n Child1 | SubChild1\n Child1 | SubChild2\n(5 rows)\n\u003c/pre\u003e\n\u003cp\u003eIn the last \u003ccode\u003eSELECT\u003c/code\u003e, notice that no output row appears for \u003ccode\u003eChild2\u003c/code\u003e, \u003ccode\u003eChild3\u003c/code\u003e, etc. This happens because \u003ccode\u003elistchildren\u003c/code\u003e returns an empty set for those arguments, so no result rows are generated. This is the same behavior as we got from an inner join to the function result when using the \u003ccode\u003eLATERAL\u003c/code\u003e syntax.\u003c/p\u003e\n\u003cp\u003e\u003cspan\u003ePostgreSQL\u003c/span\u003e\u0026#39;s behavior for a set-returning function in a query\u0026#39;s select list is almost exactly the same as if the set-returning function had been written in a \u003ccode\u003eLATERAL FROM\u003c/code\u003e-clause item instead. For example,\u003c/p\u003e\n\u003cpre\u003eSELECT x, generate_series(1,5) AS g FROM tab;\n\u003c/pre\u003e\n\u003cp\u003eis almost equivalent to\u003c/p\u003e\n\u003cpre\u003eSELECT x, g FROM tab, LATERAL generate_series(1,5) AS g;\n\u003c/pre\u003e\n\u003cp\u003eIt would be exactly the same, except that in this specific example, the planner could choose to put \u003ccode\u003eg\u003c/code\u003e on the outside of the nested-loop join, since \u003ccode\u003eg\u003c/code\u003e has no actual lateral dependency on \u003ccode\u003etab\u003c/code\u003e. That would result in a different output row order. Set-returning functions in the select list are always evaluated as though they are on the inside of a nested-loop join with the rest of the \u003ccode\u003eFROM\u003c/code\u003e clause, so that the function(s) are run to completion before the next row from the \u003ccode\u003eFROM\u003c/code\u003e clause is considered.\u003c/p\u003e\n\u003cp\u003eIf there is more than one set-returning function in the query\u0026#39;s select list, the behavior is similar to what you get from putting the functions into a single \u003ccode\u003eLATERAL ROWS FROM( ... )\u003c/code\u003e \u003ccode\u003eFROM\u003c/code\u003e-clause item. For each row from the underlying query, there is an output row using the first result from each function, then an output row using the second result, and so on. If some of the set-returning functions produce fewer outputs than others, null values are substituted for the missing data, so that the total number of rows emitted for one underlying row is the same as for the set-returning function that produced the most outputs. Thus the set-returning functions run \u003cspan\u003e“\u003cspan\u003ein lockstep\u003c/span\u003e”\u003c/span\u003e until they are all exhausted, and then execution continues with the next underlying row.\u003c/p\u003e\n\u003cp\u003eSet-returning functions can be nested in a select list, although that is not allowed in \u003ccode\u003eFROM\u003c/code\u003e-clause items. In such cases, each level of nesting is treated separately, as though it were a separate \u003ccode\u003eLATERAL ROWS FROM( ... )\u003c/code\u003e item. For example, in\u003c/p\u003e\n\u003cpre\u003eSELECT srf1(srf2(x), srf3(y)), srf4(srf5(z)) FROM tab;\n\u003c/pre\u003e\n\u003cp\u003ethe set-returning functions \u003ccode\u003esrf2\u003c/code\u003e, \u003ccode\u003esrf3\u003c/code\u003e, and \u003ccode\u003esrf5\u003c/code\u003e would be run in lockstep for each row of \u003ccode\u003etab\u003c/code\u003e, and then \u003ccode\u003esrf1\u003c/code\u003e and \u003ccode\u003esrf4\u003c/code\u003e would be applied in lockstep to each row produced by the lower functions.\u003c/p\u003e\n\u003cp\u003eSet-returning functions cannot be used within conditional-evaluation constructs, such as \u003ccode\u003eCASE\u003c/code\u003e or \u003ccode\u003eCOALESCE\u003c/code\u003e. For example, consider\u003c/p\u003e\n\u003cpre\u003eSELECT x, CASE WHEN x \u0026gt; 0 THEN generate_series(1, 5) ELSE 0 END FROM tab;\n\u003c/pre\u003e\n\u003cp\u003eIt might seem that this should produce five repetitions of input rows that have \u003ccode\u003ex \u0026gt; 0\u003c/code\u003e, and a single repetition of those that do not; but actually, because \u003ccode\u003egenerate_series(1, 5)\u003c/code\u003e would be run in an implicit \u003ccode\u003eLATERAL FROM\u003c/code\u003e item before the \u003ccode\u003eCASE\u003c/code\u003e expression is ever evaluated, it would produce five repetitions of every input row. To reduce confusion, such cases produce a parse-time error instead.\u003c/p\u003e\n\u003cdiv\u003e\n\u003ch3\u003eNote\u003c/h3\u003e\n\u003cp\u003eIf a function\u0026#39;s last command is \u003ccode\u003eINSERT\u003c/code\u003e, \u003ccode\u003eUPDATE\u003c/code\u003e, \u003ccode\u003eDELETE\u003c/code\u003e, or \u003ccode\u003eMERGE\u003c/code\u003e with \u003ccode\u003eRETURNING\u003c/code\u003e, that command will always be executed to completion, even if the function is not declared with \u003ccode\u003eSETOF\u003c/code\u003e or the calling query does not fetch all the result rows. Any extra rows produced by the \u003ccode\u003eRETURNING\u003c/code\u003e clause are silently dropped, but the commanded table modifications still happen (and are all completed before returning from the function).\u003c/p\u003e\n\u003c/div\u003e\n\u003cdiv\u003e\n\u003ch3\u003eNote\u003c/h3\u003e\n\u003cp\u003eBefore \u003cspan\u003ePostgreSQL\u003c/span\u003e 10, putting more than one set-returning function in the same select list did not behave very sensibly unless they always produced equal numbers of rows. Otherwise, what you got was a number of output rows equal to the least common multiple of the numbers of rows produced by the set-returning functions. Also, nested set-returning functions did not work as described above; instead, a set-returning function could have at most one set-returning argument, and each nest of set-returning functions was run independently. Also, conditional execution (set-returning functions inside \u003ccode\u003eCASE\u003c/code\u003e etc.) was previously allowed, complicating things even more. Use of the \u003ccode\u003eLATERAL\u003c/code\u003e syntax is recommended when writing queries that need to work in older \u003cspan\u003ePostgreSQL\u003c/span\u003e versions, because that will give consistent results across different versions. If you have a query that is relying on conditional execution of a set-returning function, you may be able to fix it by moving the conditional test into a custom set-returning function. For example,\u003c/p\u003e\n\u003cpre\u003eSELECT x, CASE WHEN y \u0026gt; 0 THEN generate_series(1, z) ELSE 5 END FROM tab;\n\u003c/pre\u003e\n\u003cp\u003ecould become\u003c/p\u003e\n\u003cpre\u003eCREATE FUNCTION case_generate_series(cond bool, start int, fin int, els int)\n  RETURNS SETOF int AS $$\nBEGIN\n  IF cond THEN\n    RETURN QUERY SELECT generate_series(start, fin);\n  ELSE\n    RETURN QUERY SELECT els;\n  END IF;\nEND$$ LANGUAGE plpgsql;\n\nSELECT x, case_generate_series(y \u0026gt; 0, 1, z, 5) FROM tab;\n\u003c/pre\u003e\n\u003cp\u003eThis formulation will work the same in all versions of \u003cspan\u003ePostgreSQL\u003c/span\u003e.\u003c/p\u003e\n\u003c/div\u003e\n\u003c/div\u003e\n\u003cdiv id=\"XFUNC-SQL-FUNCTIONS-RETURNING-TABLE\"\u003e\n\u003cdiv\u003e\n\u003cdiv\u003e\n\u003cdiv\u003e\n\u003ch3\u003e36.5.10. SQL Functions Returning \u003ccode\u003eTABLE\u003c/code\u003e \u003c/h3\u003e\n\u003c/div\u003e\n\u003c/div\u003e\n\u003c/div\u003e\n\u003cp\u003eThere is another way to declare a function as returning a set, which is to use the syntax \u003ccode\u003eRETURNS TABLE(\u003cem\u003e\u003ccode\u003ecolumns\u003c/code\u003e\u003c/em\u003e)\u003c/code\u003e. This is equivalent to using one or more \u003ccode\u003eOUT\u003c/code\u003e parameters plus marking the function as returning \u003ccode\u003eSETOF record\u003c/code\u003e (or \u003ccode\u003eSETOF\u003c/code\u003e a single output parameter\u0026#39;s type, as appropriate). This notation is specified in recent versions of the SQL standard, and thus may be more portable than using \u003ccode\u003eSETOF\u003c/code\u003e.\u003c/p\u003e\n\u003cp\u003eFor example, the preceding sum-and-product example could also be done this way:\u003c/p\u003e\n\u003cpre\u003eCREATE FUNCTION sum_n_product_with_tab (x int)\nRETURNS TABLE(sum int, product int) AS $$\n    SELECT $1 + tab.y, $1 * tab.y FROM tab;\n$$ LANGUAGE SQL;\n\u003c/pre\u003e\n\u003cp\u003eIt is not allowed to use explicit \u003ccode\u003eOUT\u003c/code\u003e or \u003ccode\u003eINOUT\u003c/code\u003e parameters with the \u003ccode\u003eRETURNS TABLE\u003c/code\u003e notation — you must put all the output columns in the \u003ccode\u003eTABLE\u003c/code\u003e list.\u003c/p\u003e\n\u003c/div\u003e\n\u003cdiv id=\"XFUNC-SQL-POLYMORPHIC-FUNCTIONS\"\u003e\n\u003cdiv\u003e\n\u003cdiv\u003e\n\u003cdiv\u003e\n\u003ch3\u003e36.5.11. Polymorphic SQL Functions \u003c/h3\u003e\n\u003c/div\u003e\n\u003c/div\u003e\n\u003c/div\u003e\n\u003cp\u003eSQL functions can be declared to accept and return the polymorphic types described in \u003ca href=\"/docs/18/extend-type-system.html#EXTEND-TYPES-POLYMORPHIC\" rel=\"nofollow\"\u003eSection 36.2.5\u003c/a\u003e. Here is a polymorphic function \u003ccode\u003emake_array\u003c/code\u003e that builds up an array from two arbitrary data type elements:\u003c/p\u003e\n\u003cpre\u003eCREATE FUNCTION make_array(anyelement, anyelement) RETURNS anyarray AS $$\n    SELECT ARRAY[$1, $2];\n$$ LANGUAGE SQL;\n\nSELECT make_array(1, 2) AS intarray, make_array(\u0026#39;a\u0026#39;::text, \u0026#39;b\u0026#39;) AS textarray;\n intarray | textarray\n----------+-----------\n {1,2}    | {a,b}\n(1 row)\n\u003c/pre\u003e\n\u003cp\u003eNotice the use of the typecast \u003ccode\u003e\u0026#39;a\u0026#39;::text\u003c/code\u003e to specify that the argument is of type \u003ccode\u003etext\u003c/code\u003e. This is required if the argument is just a string literal, since otherwise it would be treated as type \u003ccode\u003eunknown\u003c/code\u003e, and array of \u003ccode\u003eunknown\u003c/code\u003e is not a valid type. Without the typecast, you will get errors like this:\u003c/p\u003e\n\u003cpre\u003eERROR:  could not determine polymorphic type because input has type unknown\n\u003c/pre\u003e\n\u003cp\u003eWith \u003ccode\u003emake_array\u003c/code\u003e declared as above, you must provide two arguments that are of exactly the same data type; the system will not attempt to resolve any type differences. Thus for example this does not work:\u003c/p\u003e\n\u003cpre\u003eSELECT make_array(1, 2.5) AS numericarray;\nERROR:  function make_array(integer, numeric) does not exist\n\u003c/pre\u003e\n\u003cp\u003eAn alternative approach is to use the \u003cspan\u003e“\u003cspan\u003ecommon\u003c/span\u003e”\u003c/span\u003e family of polymorphic types, which allows the system to try to identify a suitable common type:\u003c/p\u003e\n\u003cpre\u003eCREATE FUNCTION make_array2(anycompatible, anycompatible)\nRETURNS anycompatiblearray AS $$\n    SELECT ARRAY[$1, $2];\n$$ LANGUAGE SQL;\n\nSELECT make_array2(1, 2.5) AS numericarray;\n numericarray\n--------------\n {1,2.5}\n(1 row)\n\u003c/pre\u003e\n\u003cp\u003eBecause the rules for common type resolution default to choosing type \u003ccode\u003etext\u003c/code\u003e when all inputs are of unknown types, this also works:\u003c/p\u003e\n\u003cpre\u003eSELECT make_array2(\u0026#39;a\u0026#39;, \u0026#39;b\u0026#39;) AS textarray;\n textarray\n-----------\n {a,b}\n(1 row)\n\u003c/pre\u003e\n\u003cp\u003eIt is permitted to have polymorphic arguments with a fixed return type, but the converse is not. For example:\u003c/p\u003e\n\u003cpre\u003eCREATE FUNCTION is_greater(anyelement, anyelement) RETURNS boolean AS $$\n    SELECT $1 \u0026gt; $2;\n$$ LANGUAGE SQL;\n\nSELECT is_greater(1, 2);\n is_greater\n------------\n f\n(1 row)\n\nCREATE FUNCTION invalid_func() RETURNS anyelement AS $$\n    SELECT 1;\n$$ LANGUAGE SQL;\nERROR:  cannot determine result data type\nDETAIL:  A result of type anyelement requires at least one input of type anyelement, anyarray, anynonarray, anyenum, or anyrange.\n\u003c/pre\u003e\n\u003cp\u003ePolymorphism can be used with functions that have output arguments. For example:\u003c/p\u003e\n\u003cpre\u003eCREATE FUNCTION dup (f1 anyelement, OUT f2 anyelement, OUT f3 anyarray)\nAS \u0026#39;select $1, array[$1,$1]\u0026#39; LANGUAGE SQL;\n\nSELECT * FROM dup(22);\n f2 |   f3\n----+---------\n 22 | {22,22}\n(1 row)\n\u003c/pre\u003e\n\u003cp\u003ePolymorphism can also be used with variadic functions. For example:\u003c/p\u003e\n\u003cpre\u003eCREATE FUNCTION anyleast (VARIADIC anyarray) RETURNS anyelement AS $$\n    SELECT min($1[i]) FROM generate_subscripts($1, 1) g(i);\n$$ LANGUAGE SQL;\n\nSELECT anyleast(10, -1, 5, 4);\n anyleast\n----------\n       -1\n(1 row)\n\nSELECT anyleast(\u0026#39;abc\u0026#39;::text, \u0026#39;def\u0026#39;);\n anyleast\n----------\n abc\n(1 row)\n\nCREATE FUNCTION concat_values(text, VARIADIC anyarray) RETURNS text AS $$\n    SELECT array_to_string($2, $1);\n$$ LANGUAGE SQL;\n\nSELECT concat_values(\u0026#39;|\u0026#39;, 1, 4, 2);\n concat_values\n---------------\n 1|4|2\n(1 row)\n\u003c/pre\u003e\n\u003c/div\u003e\n\u003cdiv id=\"XFUNC-SQL-COLLATIONS\"\u003e\n\u003cdiv\u003e\n\u003cdiv\u003e\n\u003cdiv\u003e\n\u003ch3\u003e36.5.12. SQL Functions with Collations \u003c/h3\u003e\n\u003c/div\u003e\n\u003c/div\u003e\n\u003c/div\u003e\n\u003cp\u003eWhen an SQL function has one or more parameters of collatable data types, a collation is identified for each function call depending on the collations assigned to the actual arguments, as described in \u003ca href=\"/docs/18/collation.html\" rel=\"nofollow\"\u003eSection 23.2\u003c/a\u003e. If a collation is successfully identified (i.e., there are no conflicts of implicit collations among the arguments) then all the collatable parameters are treated as having that collation implicitly. This will affect the behavior of collation-sensitive operations within the function. For example, using the \u003ccode\u003eanyleast\u003c/code\u003e function described above, the result of\u003c/p\u003e\n\u003cpre\u003eSELECT anyleast(\u0026#39;abc\u0026#39;::text, \u0026#39;ABC\u0026#39;);\n\u003c/pre\u003e\n\u003cp\u003ewill depend on the database\u0026#39;s default collation. In \u003ccode\u003eC\u003c/code\u003e locale the result will be \u003ccode\u003eABC\u003c/code\u003e, but in many other locales it will be \u003ccode\u003eabc\u003c/code\u003e. The collation to use can be forced by adding a \u003ccode\u003eCOLLATE\u003c/code\u003e clause to any of the arguments, for example\u003c/p\u003e\n\u003cpre\u003eSELECT anyleast(\u0026#39;abc\u0026#39;::text, \u0026#39;ABC\u0026#39; COLLATE \u0026#34;C\u0026#34;);\n\u003c/pre\u003e\n\u003cp\u003eAlternatively, if you wish a function to operate with a particular collation regardless of what it is called with, insert \u003ccode\u003eCOLLATE\u003c/code\u003e clauses as needed in the function definition. This version of \u003ccode\u003eanyleast\u003c/code\u003e would always use \u003ccode\u003een_US\u003c/code\u003e locale to compare strings:\u003c/p\u003e\n\u003cpre\u003eCREATE FUNCTION anyleast (VARIADIC anyarray) RETURNS anyelement AS $$\n    SELECT min($1[i] COLLATE \u0026#34;en_US\u0026#34;) FROM generate_subscripts($1, 1) g(i);\n$$ LANGUAGE SQL;\n\u003c/pre\u003e\n\u003cp\u003eBut note that this will throw an error if applied to a non-collatable data type.\u003c/p\u003e\n\u003cp\u003eIf no common collation can be identified among the actual arguments, then an SQL function treats its parameters as having their data types\u0026#39; default collation (which is usually the database\u0026#39;s default collation, but could be different for parameters of domain types).\u003c/p\u003e\n\u003cp\u003eThe behavior of collatable parameters can be thought of as a limited form of polymorphism, applicable only to textual data types.\u003c/p\u003e\n\u003c/div\u003e\n\u003c/div\u003e","SourceRevision":"555610c24d53e4316da5b7d3fc25c279d96856d5e0e23ee308c328c5fa881d9f","ContentHash":"e13aa62529792ce79a54aeae300eb4cdc1ba36d94fae9aa78c1ed10fee42c8ee","Payload":{"description":["SQL-language functions"],"manual_html":"\u003cdiv class=\"sect1\" id=\"XFUNC-SQL\"\u003e\n\u003cdiv class=\"titlepage\"\u003e\n\u003cdiv\u003e\n\u003cdiv\u003e\n\u003ch2 class=\"title\"\u003e36.5. Query Language (SQL) Functions \u003c/h2\u003e\n\u003c/div\u003e\n\u003c/div\u003e\n\u003c/div\u003e\n\n\u003cp\u003eSQL functions execute an arbitrary list of SQL statements, returning the result of the last query in the list. In the simple (non-set) case, the first row of the last query's result will be returned. (Bear in mind that \u003cspan class=\"quote\"\u003e“\u003cspan class=\"quote\"\u003ethe first row\u003c/span\u003e”\u003c/span\u003e of a multirow result is not well-defined unless you use \u003ccode class=\"literal\"\u003eORDER BY\u003c/code\u003e.) If the last query happens to return no rows at all, the null value will be returned.\u003c/p\u003e\n\u003cp\u003eAlternatively, an SQL function can be declared to return a set (that is, multiple rows) by specifying the function's return type as \u003ccode class=\"literal\"\u003eSETOF \u003cem class=\"replaceable\"\u003e\u003ccode\u003esometype\u003c/code\u003e\u003c/em\u003e\u003c/code\u003e, or equivalently by declaring it as \u003ccode class=\"literal\"\u003eRETURNS TABLE(\u003cem class=\"replaceable\"\u003e\u003ccode\u003ecolumns\u003c/code\u003e\u003c/em\u003e)\u003c/code\u003e. In this case all rows of the last query's result are returned. Further details appear below.\u003c/p\u003e\n\u003cp\u003eThe body of an SQL function must be a list of SQL statements separated by semicolons. A semicolon after the last statement is optional. Unless the function is declared to return \u003ccode class=\"type\"\u003evoid\u003c/code\u003e, the last statement must be a \u003ccode class=\"command\"\u003eSELECT\u003c/code\u003e, or an \u003ccode class=\"command\"\u003eINSERT\u003c/code\u003e, \u003ccode class=\"command\"\u003eUPDATE\u003c/code\u003e, \u003ccode class=\"command\"\u003eDELETE\u003c/code\u003e, or \u003ccode class=\"command\"\u003eMERGE\u003c/code\u003e that has a \u003ccode class=\"literal\"\u003eRETURNING\u003c/code\u003e clause.\u003c/p\u003e\n\u003cp\u003eAny collection of commands in the SQL language can be packaged together and defined as a function. Besides \u003ccode class=\"command\"\u003eSELECT\u003c/code\u003e queries, the commands can include data modification queries (\u003ccode class=\"command\"\u003eINSERT\u003c/code\u003e, \u003ccode class=\"command\"\u003eUPDATE\u003c/code\u003e, \u003ccode class=\"command\"\u003eDELETE\u003c/code\u003e, and \u003ccode class=\"command\"\u003eMERGE\u003c/code\u003e), as well as other SQL commands. (You cannot use transaction control commands, e.g., \u003ccode class=\"command\"\u003eCOMMIT\u003c/code\u003e, \u003ccode class=\"command\"\u003eSAVEPOINT\u003c/code\u003e, and some utility commands, e.g., \u003ccode class=\"literal\"\u003eVACUUM\u003c/code\u003e, in SQL functions.) However, the final command must be a \u003ccode class=\"command\"\u003eSELECT\u003c/code\u003e or have a \u003ccode class=\"literal\"\u003eRETURNING\u003c/code\u003e clause that returns whatever is specified as the function's return type. Alternatively, if you want to define an SQL function that performs actions but has no useful value to return, you can define it as returning \u003ccode class=\"type\"\u003evoid\u003c/code\u003e. For example, this function removes rows with negative salaries from the \u003ccode class=\"literal\"\u003eemp\u003c/code\u003e table:\u003c/p\u003e\n\u003cpre class=\"screen\"\u003eCREATE FUNCTION clean_emp() RETURNS void AS '\n    DELETE FROM emp\n        WHERE salary \u0026lt; 0;\n' LANGUAGE SQL;\n\nSELECT clean_emp();\n\n clean_emp\n-----------\n\n(1 row)\n\u003c/pre\u003e\n\u003cp\u003eYou can also write this as a procedure, thus avoiding the issue of the return type. For example:\u003c/p\u003e\n\u003cpre class=\"screen\"\u003eCREATE PROCEDURE clean_emp() AS '\n    DELETE FROM emp\n        WHERE salary \u0026lt; 0;\n' LANGUAGE SQL;\n\nCALL clean_emp();\n\u003c/pre\u003e\n\u003cp\u003eIn simple cases like this, the difference between a function returning \u003ccode class=\"type\"\u003evoid\u003c/code\u003e and a procedure is mostly stylistic. However, procedures offer additional functionality such as transaction control that is not available in functions. Also, procedures are SQL standard whereas returning \u003ccode class=\"type\"\u003evoid\u003c/code\u003e is a PostgreSQL extension.\u003c/p\u003e\n\u003cp\u003eThe syntax of the \u003ccode class=\"command\"\u003eCREATE FUNCTION\u003c/code\u003e command requires the function body to be written as a string constant. It is usually most convenient to use dollar quoting (see \u003ca class=\"xref\" href=\"/docs/18/sql-syntax-lexical.html#SQL-SYNTAX-DOLLAR-QUOTING\" title=\"4.1.2.4. Dollar-Quoted String Constants\"\u003eSection 4.1.2.4\u003c/a\u003e) for the string constant. If you choose to use regular single-quoted string constant syntax, you must double single quote marks (\u003ccode class=\"literal\"\u003e'\u003c/code\u003e) and backslashes (\u003ccode class=\"literal\"\u003e\\\u003c/code\u003e) (assuming escape string syntax) in the body of the function (see \u003ca class=\"xref\" href=\"/docs/18/sql-syntax-lexical.html#SQL-SYNTAX-STRINGS\" title=\"4.1.2.1. String Constants\"\u003eSection 4.1.2.1\u003c/a\u003e).\u003c/p\u003e\n\u003cdiv class=\"sect2\" id=\"XFUNC-SQL-FUNCTION-ARGUMENTS\"\u003e\n\u003cdiv class=\"titlepage\"\u003e\n\u003cdiv\u003e\n\u003cdiv\u003e\n\u003ch3 class=\"title\"\u003e36.5.1. Arguments for SQL Functions \u003c/h3\u003e\n\u003c/div\u003e\n\u003c/div\u003e\n\u003c/div\u003e\n\u003cp\u003eArguments of an SQL function can be referenced in the function body using either names or numbers. Examples of both methods appear below.\u003c/p\u003e\n\u003cp\u003eTo use a name, declare the function argument as having a name, and then just write that name in the function body. If the argument name is the same as any column name in the current SQL command within the function, the column name will take precedence. To override this, qualify the argument name with the name of the function itself, that is \u003ccode class=\"literal\"\u003e\u003cem class=\"replaceable\"\u003e\u003ccode\u003efunction_name\u003c/code\u003e\u003c/em\u003e.\u003cem class=\"replaceable\"\u003e\u003ccode\u003eargument_name\u003c/code\u003e\u003c/em\u003e\u003c/code\u003e. (If this would conflict with a qualified column name, again the column name wins. You can avoid the ambiguity by choosing a different alias for the table within the SQL command.)\u003c/p\u003e\n\u003cp\u003eIn the older numeric approach, arguments are referenced using the syntax \u003ccode class=\"literal\"\u003e$\u003cem class=\"replaceable\"\u003e\u003ccode\u003en\u003c/code\u003e\u003c/em\u003e\u003c/code\u003e: \u003ccode class=\"literal\"\u003e$1\u003c/code\u003e refers to the first input argument, \u003ccode class=\"literal\"\u003e$2\u003c/code\u003e to the second, and so on. This will work whether or not the particular argument was declared with a name.\u003c/p\u003e\n\u003cp\u003eIf an argument is of a composite type, then the dot notation, e.g., \u003ccode class=\"literal\"\u003e\u003cem class=\"replaceable\"\u003e\u003ccode\u003eargname\u003c/code\u003e\u003c/em\u003e.\u003cem class=\"replaceable\"\u003e\u003ccode\u003efieldname\u003c/code\u003e\u003c/em\u003e\u003c/code\u003e or \u003ccode class=\"literal\"\u003e$1.\u003cem class=\"replaceable\"\u003e\u003ccode\u003efieldname\u003c/code\u003e\u003c/em\u003e\u003c/code\u003e, can be used to access attributes of the argument. Again, you might need to qualify the argument's name with the function name to make the form with an argument name unambiguous.\u003c/p\u003e\n\u003cp\u003eSQL function arguments can only be used as data values, not as identifiers. Thus for example this is reasonable:\u003c/p\u003e\n\u003cpre class=\"programlisting\"\u003eINSERT INTO mytable VALUES ($1);\n\u003c/pre\u003e\n\u003cp\u003ebut this will not work:\u003c/p\u003e\n\u003cpre class=\"programlisting\"\u003eINSERT INTO $1 VALUES (42);\n\u003c/pre\u003e\n\u003cdiv class=\"note\"\u003e\n\u003ch3 class=\"title\"\u003eNote\u003c/h3\u003e\n\u003cp\u003eThe ability to use names to reference SQL function arguments was added in \u003cspan class=\"productname\"\u003ePostgreSQL\u003c/span\u003e 9.2. Functions to be used in older servers must use the \u003ccode class=\"literal\"\u003e$\u003cem class=\"replaceable\"\u003e\u003ccode\u003en\u003c/code\u003e\u003c/em\u003e\u003c/code\u003e notation.\u003c/p\u003e\n\u003c/div\u003e\n\u003c/div\u003e\n\u003cdiv class=\"sect2\" id=\"XFUNC-SQL-BASE-FUNCTIONS\"\u003e\n\u003cdiv class=\"titlepage\"\u003e\n\u003cdiv\u003e\n\u003cdiv\u003e\n\u003ch3 class=\"title\"\u003e36.5.2. SQL Functions on Base Types \u003c/h3\u003e\n\u003c/div\u003e\n\u003c/div\u003e\n\u003c/div\u003e\n\u003cp\u003eThe simplest possible SQL function has no arguments and simply returns a base type, such as \u003ccode class=\"type\"\u003einteger\u003c/code\u003e:\u003c/p\u003e\n\u003cpre class=\"screen\"\u003eCREATE FUNCTION one() RETURNS integer AS $$\n    SELECT 1 AS result;\n$$ LANGUAGE SQL;\n\n-- Alternative syntax for string literal:\nCREATE FUNCTION one() RETURNS integer AS '\n    SELECT 1 AS result;\n' LANGUAGE SQL;\n\nSELECT one();\n\n one\n-----\n   1\n\u003c/pre\u003e\n\u003cp\u003eNotice that we defined a column alias within the function body for the result of the function (with the name \u003ccode class=\"literal\"\u003eresult\u003c/code\u003e), but this column alias is not visible outside the function. Hence, the result is labeled \u003ccode class=\"literal\"\u003eone\u003c/code\u003e instead of \u003ccode class=\"literal\"\u003eresult\u003c/code\u003e.\u003c/p\u003e\n\u003cp\u003eIt is almost as easy to define SQL functions that take base types as arguments:\u003c/p\u003e\n\u003cpre class=\"screen\"\u003eCREATE FUNCTION add_em(x integer, y integer) RETURNS integer AS $$\n    SELECT x + y;\n$$ LANGUAGE SQL;\n\nSELECT add_em(1, 2) AS answer;\n\n answer\n--------\n      3\n\u003c/pre\u003e\n\u003cp\u003eAlternatively, we could dispense with names for the arguments and use numbers:\u003c/p\u003e\n\u003cpre class=\"screen\"\u003eCREATE FUNCTION add_em(integer, integer) RETURNS integer AS $$\n    SELECT $1 + $2;\n$$ LANGUAGE SQL;\n\nSELECT add_em(1, 2) AS answer;\n\n answer\n--------\n      3\n\u003c/pre\u003e\n\u003cp\u003eHere is a more useful function, which might be used to debit a bank account:\u003c/p\u003e\n\u003cpre class=\"programlisting\"\u003eCREATE FUNCTION tf1 (accountno integer, debit numeric) RETURNS numeric AS $$\n    UPDATE bank\n        SET balance = balance - debit\n        WHERE accountno = tf1.accountno;\n    SELECT 1;\n$$ LANGUAGE SQL;\n\u003c/pre\u003e\n\u003cp\u003eA user could execute this function to debit account 17 by $100.00 as follows:\u003c/p\u003e\n\u003cpre class=\"programlisting\"\u003eSELECT tf1(17, 100.0);\n\u003c/pre\u003e\n\u003cp\u003eIn this example, we chose the name \u003ccode class=\"literal\"\u003eaccountno\u003c/code\u003e for the first argument, but this is the same as the name of a column in the \u003ccode class=\"literal\"\u003ebank\u003c/code\u003e table. Within the \u003ccode class=\"command\"\u003eUPDATE\u003c/code\u003e command, \u003ccode class=\"literal\"\u003eaccountno\u003c/code\u003e refers to the column \u003ccode class=\"literal\"\u003ebank.accountno\u003c/code\u003e, so \u003ccode class=\"literal\"\u003etf1.accountno\u003c/code\u003e must be used to refer to the argument. We could of course avoid this by using a different name for the argument.\u003c/p\u003e\n\u003cp\u003eIn practice one would probably like a more useful result from the function than a constant 1, so a more likely definition is:\u003c/p\u003e\n\u003cpre class=\"programlisting\"\u003eCREATE FUNCTION tf1 (accountno integer, debit numeric) RETURNS numeric AS $$\n    UPDATE bank\n        SET balance = balance - debit\n        WHERE accountno = tf1.accountno;\n    SELECT balance FROM bank WHERE accountno = tf1.accountno;\n$$ LANGUAGE SQL;\n\u003c/pre\u003e\n\u003cp\u003ewhich adjusts the balance and returns the new balance. The same thing could be done in one command using \u003ccode class=\"literal\"\u003eRETURNING\u003c/code\u003e:\u003c/p\u003e\n\u003cpre class=\"programlisting\"\u003eCREATE FUNCTION tf1 (accountno integer, debit numeric) RETURNS numeric AS $$\n    UPDATE bank\n        SET balance = balance - debit\n        WHERE accountno = tf1.accountno\n    RETURNING balance;\n$$ LANGUAGE SQL;\n\u003c/pre\u003e\n\u003cp\u003eIf the final \u003ccode class=\"literal\"\u003eSELECT\u003c/code\u003e or \u003ccode class=\"literal\"\u003eRETURNING\u003c/code\u003e clause in an SQL function does not return exactly the function's declared result type, \u003cspan class=\"productname\"\u003ePostgreSQL\u003c/span\u003e will automatically cast the value to the required type, if that is possible with an implicit or assignment cast. Otherwise, you must write an explicit cast. For example, suppose we wanted the previous \u003ccode class=\"function\"\u003eadd_em\u003c/code\u003e function to return type \u003ccode class=\"type\"\u003efloat8\u003c/code\u003e instead. It's sufficient to write\u003c/p\u003e\n\u003cpre class=\"programlisting\"\u003eCREATE FUNCTION add_em(integer, integer) RETURNS float8 AS $$\n    SELECT $1 + $2;\n$$ LANGUAGE SQL;\n\u003c/pre\u003e\n\u003cp\u003esince the \u003ccode class=\"type\"\u003einteger\u003c/code\u003e sum can be implicitly cast to \u003ccode class=\"type\"\u003efloat8\u003c/code\u003e. (See \u003ca class=\"xref\" href=\"/docs/18/typeconv.html\" title=\"Chapter 10. Type Conversion\"\u003eChapter 10\u003c/a\u003e or \u003ca class=\"xref\" href=\"/docs/18/sql-createcast.html\" title=\"CREATE CAST\"\u003e\u003cspan class=\"refentrytitle\"\u003eCREATE CAST\u003c/span\u003e\u003c/a\u003e for more about casts.)\u003c/p\u003e\n\u003c/div\u003e\n\u003cdiv class=\"sect2\" id=\"XFUNC-SQL-COMPOSITE-FUNCTIONS\"\u003e\n\u003cdiv class=\"titlepage\"\u003e\n\u003cdiv\u003e\n\u003cdiv\u003e\n\u003ch3 class=\"title\"\u003e36.5.3. SQL Functions on Composite Types \u003c/h3\u003e\n\u003c/div\u003e\n\u003c/div\u003e\n\u003c/div\u003e\n\u003cp\u003eWhen writing functions with arguments of composite types, we must not only specify which argument we want but also the desired attribute (field) of that argument. For example, suppose that \u003ccode class=\"type\"\u003eemp\u003c/code\u003e is a table containing employee data, and therefore also the name of the composite type of each row of the table. Here is a function \u003ccode class=\"function\"\u003edouble_salary\u003c/code\u003e that computes what someone's salary would be if it were doubled:\u003c/p\u003e\n\u003cpre class=\"screen\"\u003eCREATE TABLE emp (\n    name        text,\n    salary      numeric,\n    age         integer,\n    cubicle     point\n);\n\nINSERT INTO emp VALUES ('Bill', 4200, 45, '(2,1)');\n\nCREATE FUNCTION double_salary(emp) RETURNS numeric AS $$\n    SELECT $1.salary * 2 AS salary;\n$$ LANGUAGE SQL;\n\nSELECT name, double_salary(emp.*) AS dream\n    FROM emp\n    WHERE emp.cubicle ~= point '(2,1)';\n\n name | dream\n------+-------\n Bill |  8400\n\u003c/pre\u003e\n\u003cp\u003eNotice the use of the syntax \u003ccode class=\"literal\"\u003e$1.salary\u003c/code\u003e to select one field of the argument row value. Also notice how the calling \u003ccode class=\"command\"\u003eSELECT\u003c/code\u003e command uses \u003cem class=\"replaceable\"\u003e\u003ccode\u003etable_name\u003c/code\u003e\u003c/em\u003e\u003ccode class=\"literal\"\u003e.*\u003c/code\u003e to select the entire current row of a table as a composite value. The table row can alternatively be referenced using just the table name, like this:\u003c/p\u003e\n\u003cpre class=\"screen\"\u003eSELECT name, double_salary(emp) AS dream\n    FROM emp\n    WHERE emp.cubicle ~= point '(2,1)';\n\u003c/pre\u003e\n\u003cp\u003ebut this usage is deprecated since it's easy to get confused. (See \u003ca class=\"xref\" href=\"/docs/18/rowtypes.html#ROWTYPES-USAGE\" title=\"8.16.5. Using Composite Types in Queries\"\u003eSection 8.16.5\u003c/a\u003e for details about these two notations for the composite value of a table row.)\u003c/p\u003e\n\u003cp\u003eSometimes it is handy to construct a composite argument value on-the-fly. This can be done with the \u003ccode class=\"literal\"\u003eROW\u003c/code\u003e construct. For example, we could adjust the data being passed to the function:\u003c/p\u003e\n\u003cpre class=\"screen\"\u003eSELECT name, double_salary(ROW(name, salary*1.1, age, cubicle)) AS dream\n    FROM emp;\n\u003c/pre\u003e\n\u003cp\u003eIt is also possible to build a function that returns a composite type. This is an example of a function that returns a single \u003ccode class=\"type\"\u003eemp\u003c/code\u003e row:\u003c/p\u003e\n\u003cpre class=\"programlisting\"\u003eCREATE FUNCTION new_emp() RETURNS emp AS $$\n    SELECT text 'None' AS name,\n        1000.0 AS salary,\n        25 AS age,\n        point '(2,2)' AS cubicle;\n$$ LANGUAGE SQL;\n\u003c/pre\u003e\n\u003cp\u003eIn this example we have specified each of the attributes with a constant value, but any computation could have been substituted for these constants.\u003c/p\u003e\n\u003cp\u003eNote two important things about defining the function:\u003c/p\u003e\n\u003cdiv class=\"itemizedlist\"\u003e\n\u003cul class=\"itemizedlist\"\u003e\n\u003cli class=\"listitem\"\u003e\n\u003cp\u003eThe select list order in the query must be exactly the same as that in which the columns appear in the composite type. (Naming the columns, as we did above, is irrelevant to the system.)\u003c/p\u003e\n\u003c/li\u003e\n\u003cli class=\"listitem\"\u003e\n\u003cp\u003eWe must ensure each expression's type can be cast to that of the corresponding column of the composite type. Otherwise we'll get errors like this:\u003c/p\u003e\n\u003cpre class=\"screen\"\u003e\u003ccode class=\"computeroutput\"\u003e\nERROR:  return type mismatch in function declared to return emp\nDETAIL:  Final statement returns text instead of point at column 4.\n\u003c/code\u003e\n\u003c/pre\u003e\n\u003cp\u003eAs with the base-type case, the system will not insert explicit casts automatically, only implicit or assignment casts.\u003c/p\u003e\n\u003c/li\u003e\n\u003c/ul\u003e\n\u003c/div\u003e\n\u003cp\u003eA different way to define the same function is:\u003c/p\u003e\n\u003cpre class=\"programlisting\"\u003eCREATE FUNCTION new_emp() RETURNS emp AS $$\n    SELECT ROW('None', 1000.0, 25, '(2,2)')::emp;\n$$ LANGUAGE SQL;\n\u003c/pre\u003e\n\u003cp\u003eHere we wrote a \u003ccode class=\"command\"\u003eSELECT\u003c/code\u003e that returns just a single column of the correct composite type. This isn't really better in this situation, but it is a handy alternative in some cases — for example, if we need to compute the result by calling another function that returns the desired composite value. Another example is that if we are trying to write a function that returns a domain over composite, rather than a plain composite type, it is always necessary to write it as returning a single column, since there is no way to cause a coercion of the whole row result.\u003c/p\u003e\n\u003cp\u003eWe could call this function directly either by using it in a value expression:\u003c/p\u003e\n\u003cpre class=\"screen\"\u003eSELECT new_emp();\n\n         new_emp\n--------------------------\n (None,1000.0,25,\"(2,2)\")\n\u003c/pre\u003e\n\u003cp\u003eor by calling it as a table function:\u003c/p\u003e\n\u003cpre class=\"screen\"\u003eSELECT * FROM new_emp();\n\n name | salary | age | cubicle\n------+--------+-----+---------\n None | 1000.0 |  25 | (2,2)\n\u003c/pre\u003e\n\u003cp\u003eThe second way is described more fully in \u003ca class=\"xref\" href=\"/docs/18/xfunc-sql.html#XFUNC-SQL-TABLE-FUNCTIONS\" title=\"36.5.8. SQL Functions as Table Sources\"\u003eSection 36.5.8\u003c/a\u003e.\u003c/p\u003e\n\u003cp\u003eWhen you use a function that returns a composite type, you might want only one field (attribute) from its result. You can do that with syntax like this:\u003c/p\u003e\n\u003cpre class=\"screen\"\u003eSELECT (new_emp()).name;\n\n name\n------\n None\n\u003c/pre\u003e\n\u003cp\u003eThe extra parentheses are needed to keep the parser from getting confused. If you try to do it without them, you get something like this:\u003c/p\u003e\n\u003cpre class=\"screen\"\u003eSELECT new_emp().name;\nERROR:  syntax error at or near \".\"\nLINE 1: SELECT new_emp().name;\n                        ^\n\u003c/pre\u003e\n\u003cp\u003eAnother option is to use functional notation for extracting an attribute:\u003c/p\u003e\n\u003cpre class=\"screen\"\u003eSELECT name(new_emp());\n\n name\n------\n None\n\u003c/pre\u003e\n\u003cp\u003eAs explained in \u003ca class=\"xref\" href=\"/docs/18/rowtypes.html#ROWTYPES-USAGE\" title=\"8.16.5. Using Composite Types in Queries\"\u003eSection 8.16.5\u003c/a\u003e, the field notation and functional notation are equivalent.\u003c/p\u003e\n\u003cp\u003eAnother way to use a function returning a composite type is to pass the result to another function that accepts the correct row type as input:\u003c/p\u003e\n\u003cpre class=\"screen\"\u003eCREATE FUNCTION getname(emp) RETURNS text AS $$\n    SELECT $1.name;\n$$ LANGUAGE SQL;\n\nSELECT getname(new_emp());\n getname\n---------\n None\n(1 row)\n\u003c/pre\u003e\n\u003c/div\u003e\n\u003cdiv class=\"sect2\" id=\"XFUNC-OUTPUT-PARAMETERS\"\u003e\n\u003cdiv class=\"titlepage\"\u003e\n\u003cdiv\u003e\n\u003cdiv\u003e\n\u003ch3 class=\"title\"\u003e36.5.4. SQL Functions with Output Parameters \u003c/h3\u003e\n\u003c/div\u003e\n\u003c/div\u003e\n\u003c/div\u003e\n\u003cp\u003eAn alternative way of describing a function's results is to define it with \u003cem class=\"firstterm\"\u003eoutput parameters\u003c/em\u003e, as in this example:\u003c/p\u003e\n\u003cpre class=\"screen\"\u003eCREATE FUNCTION add_em (IN x int, IN y int, OUT sum int)\nAS 'SELECT x + y'\nLANGUAGE SQL;\n\nSELECT add_em(3,7);\n add_em\n--------\n     10\n(1 row)\n\u003c/pre\u003e\n\u003cp\u003eThis is not essentially different from the version of \u003ccode class=\"literal\"\u003eadd_em\u003c/code\u003e shown in \u003ca class=\"xref\" href=\"/docs/18/xfunc-sql.html#XFUNC-SQL-BASE-FUNCTIONS\" title=\"36.5.2. SQL Functions on Base Types\"\u003eSection 36.5.2\u003c/a\u003e. The real value of output parameters is that they provide a convenient way of defining functions that return several columns. For example,\u003c/p\u003e\n\u003cpre class=\"screen\"\u003eCREATE FUNCTION sum_n_product (x int, y int, OUT sum int, OUT product int)\nAS 'SELECT x + y, x * y'\nLANGUAGE SQL;\n\n SELECT * FROM sum_n_product(11,42);\n sum | product\n-----+---------\n  53 |     462\n(1 row)\n\u003c/pre\u003e\n\u003cp\u003eWhat has essentially happened here is that we have created an anonymous composite type for the result of the function. The above example has the same end result as\u003c/p\u003e\n\u003cpre class=\"screen\"\u003eCREATE TYPE sum_prod AS (sum int, product int);\n\nCREATE FUNCTION sum_n_product (int, int) RETURNS sum_prod\nAS 'SELECT $1 + $2, $1 * $2'\nLANGUAGE SQL;\n\u003c/pre\u003e\n\u003cp\u003ebut not having to bother with the separate composite type definition is often handy. Notice that the names attached to the output parameters are not just decoration, but determine the column names of the anonymous composite type. (If you omit a name for an output parameter, the system will choose a name on its own.)\u003c/p\u003e\n\u003cp\u003eNotice that output parameters are not included in the calling argument list when invoking such a function from SQL. This is because \u003cspan class=\"productname\"\u003ePostgreSQL\u003c/span\u003e considers only the input parameters to define the function's calling signature. That means also that only the input parameters matter when referencing the function for purposes such as dropping it. We could drop the above function with either of\u003c/p\u003e\n\u003cpre class=\"screen\"\u003eDROP FUNCTION sum_n_product (x int, y int, OUT sum int, OUT product int);\nDROP FUNCTION sum_n_product (int, int);\n\u003c/pre\u003e\n\u003cp\u003eParameters can be marked as \u003ccode class=\"literal\"\u003eIN\u003c/code\u003e (the default), \u003ccode class=\"literal\"\u003eOUT\u003c/code\u003e, \u003ccode class=\"literal\"\u003eINOUT\u003c/code\u003e, or \u003ccode class=\"literal\"\u003eVARIADIC\u003c/code\u003e. An \u003ccode class=\"literal\"\u003eINOUT\u003c/code\u003e parameter serves as both an input parameter (part of the calling argument list) and an output parameter (part of the result record type). \u003ccode class=\"literal\"\u003eVARIADIC\u003c/code\u003e parameters are input parameters, but are treated specially as described below.\u003c/p\u003e\n\u003c/div\u003e\n\u003cdiv class=\"sect2\" id=\"XFUNC-OUTPUT-PARAMETERS-PROC\"\u003e\n\u003cdiv class=\"titlepage\"\u003e\n\u003cdiv\u003e\n\u003cdiv\u003e\n\u003ch3 class=\"title\"\u003e36.5.5. SQL Procedures with Output Parameters \u003c/h3\u003e\n\u003c/div\u003e\n\u003c/div\u003e\n\u003c/div\u003e\n\u003cp\u003eOutput parameters are also supported in procedures, but they work a bit differently from functions. In \u003ccode class=\"command\"\u003eCALL\u003c/code\u003e commands, output parameters must be included in the argument list. For example, the bank account debiting routine from earlier could be written like this:\u003c/p\u003e\n\u003cpre class=\"programlisting\"\u003eCREATE PROCEDURE tp1 (accountno integer, debit numeric, OUT new_balance numeric) AS $$\n    UPDATE bank\n        SET balance = balance - debit\n        WHERE accountno = tp1.accountno\n    RETURNING balance;\n$$ LANGUAGE SQL;\n\u003c/pre\u003e\n\u003cp\u003eTo call this procedure, an argument matching the \u003ccode class=\"literal\"\u003eOUT\u003c/code\u003e parameter must be included. It's customary to write \u003ccode class=\"literal\"\u003eNULL\u003c/code\u003e:\u003c/p\u003e\n\u003cpre class=\"programlisting\"\u003eCALL tp1(17, 100.0, NULL);\n\u003c/pre\u003e\n\u003cp\u003eIf you write something else, it must be an expression that is implicitly coercible to the declared type of the parameter, just as for input parameters. Note however that such an expression will not be evaluated.\u003c/p\u003e\n\u003cp\u003eWhen calling a procedure from \u003cspan class=\"application\"\u003ePL/pgSQL\u003c/span\u003e, instead of writing \u003ccode class=\"literal\"\u003eNULL\u003c/code\u003e you must write a variable that will receive the procedure's output. See \u003ca class=\"xref\" href=\"/docs/18/plpgsql-control-structures.html#PLPGSQL-STATEMENTS-CALLING-PROCEDURE\" title=\"41.6.3. Calling a Procedure\"\u003eSection 41.6.3\u003c/a\u003e for details.\u003c/p\u003e\n\u003c/div\u003e\n\u003cdiv class=\"sect2\" id=\"XFUNC-SQL-VARIADIC-FUNCTIONS\"\u003e\n\u003cdiv class=\"titlepage\"\u003e\n\u003cdiv\u003e\n\u003cdiv\u003e\n\u003ch3 class=\"title\"\u003e36.5.6. SQL Functions with Variable Numbers of Arguments \u003c/h3\u003e\n\u003c/div\u003e\n\u003c/div\u003e\n\u003c/div\u003e\n\u003cp\u003eSQL functions can be declared to accept variable numbers of arguments, so long as all the \u003cspan class=\"quote\"\u003e“\u003cspan class=\"quote\"\u003eoptional\u003c/span\u003e”\u003c/span\u003e arguments are of the same data type. The optional arguments will be passed to the function as an array. The function is declared by marking the last parameter as \u003ccode class=\"literal\"\u003eVARIADIC\u003c/code\u003e; this parameter must be declared as being of an array type. For example:\u003c/p\u003e\n\u003cpre class=\"screen\"\u003eCREATE FUNCTION mleast(VARIADIC arr numeric[]) RETURNS numeric AS $$\n    SELECT min($1[i]) FROM generate_subscripts($1, 1) g(i);\n$$ LANGUAGE SQL;\n\nSELECT mleast(10, -1, 5, 4.4);\n mleast\n--------\n     -1\n(1 row)\n\u003c/pre\u003e\n\u003cp\u003eEffectively, all the actual arguments at or beyond the \u003ccode class=\"literal\"\u003eVARIADIC\u003c/code\u003e position are gathered up into a one-dimensional array, as if you had written\u003c/p\u003e\n\u003cpre class=\"screen\"\u003eSELECT mleast(ARRAY[10, -1, 5, 4.4]);    -- doesn't work\n\u003c/pre\u003e\n\u003cp\u003eYou can't actually write that, though — or at least, it will not match this function definition. A parameter marked \u003ccode class=\"literal\"\u003eVARIADIC\u003c/code\u003e matches one or more occurrences of its element type, not of its own type.\u003c/p\u003e\n\u003cp\u003eSometimes it is useful to be able to pass an already-constructed array to a variadic function; this is particularly handy when one variadic function wants to pass on its array parameter to another one. Also, this is the only secure way to call a variadic function found in a schema that permits untrusted users to create objects; see \u003ca class=\"xref\" href=\"/docs/18/typeconv-func.html\" title=\"10.3. Functions\"\u003eSection 10.3\u003c/a\u003e. You can do this by specifying \u003ccode class=\"literal\"\u003eVARIADIC\u003c/code\u003e in the call:\u003c/p\u003e\n\u003cpre class=\"screen\"\u003eSELECT mleast(VARIADIC ARRAY[10, -1, 5, 4.4]);\n\u003c/pre\u003e\n\u003cp\u003eThis prevents expansion of the function's variadic parameter into its element type, thereby allowing the array argument value to match normally. \u003ccode class=\"literal\"\u003eVARIADIC\u003c/code\u003e can only be attached to the last actual argument of a function call.\u003c/p\u003e\n\u003cp\u003eSpecifying \u003ccode class=\"literal\"\u003eVARIADIC\u003c/code\u003e in the call is also the only way to pass an empty array to a variadic function, for example:\u003c/p\u003e\n\u003cpre class=\"screen\"\u003eSELECT mleast(VARIADIC ARRAY[]::numeric[]);\n\u003c/pre\u003e\n\u003cp\u003eSimply writing \u003ccode class=\"literal\"\u003eSELECT mleast()\u003c/code\u003e does not work because a variadic parameter must match at least one actual argument. (You could define a second function also named \u003ccode class=\"literal\"\u003emleast\u003c/code\u003e, with no parameters, if you wanted to allow such calls.)\u003c/p\u003e\n\u003cp\u003eThe array element parameters generated from a variadic parameter are treated as not having any names of their own. This means it is not possible to call a variadic function using named arguments (\u003ca class=\"xref\" href=\"/docs/18/sql-syntax-calling-funcs.html\" title=\"4.3. Calling Functions\"\u003eSection 4.3\u003c/a\u003e), except when you specify \u003ccode class=\"literal\"\u003eVARIADIC\u003c/code\u003e. For example, this will work:\u003c/p\u003e\n\u003cpre class=\"screen\"\u003eSELECT mleast(VARIADIC arr =\u0026gt; ARRAY[10, -1, 5, 4.4]);\n\u003c/pre\u003e\n\u003cp\u003ebut not these:\u003c/p\u003e\n\u003cpre class=\"screen\"\u003eSELECT mleast(arr =\u0026gt; 10);\nSELECT mleast(arr =\u0026gt; ARRAY[10, -1, 5, 4.4]);\n\u003c/pre\u003e\n\u003c/div\u003e\n\u003cdiv class=\"sect2\" id=\"XFUNC-SQL-PARAMETER-DEFAULTS\"\u003e\n\u003cdiv class=\"titlepage\"\u003e\n\u003cdiv\u003e\n\u003cdiv\u003e\n\u003ch3 class=\"title\"\u003e36.5.7. SQL Functions with Default Values for Arguments \u003c/h3\u003e\n\u003c/div\u003e\n\u003c/div\u003e\n\u003c/div\u003e\n\u003cp\u003eFunctions can be declared with default values for some or all input arguments. The default values are inserted whenever the function is called with insufficiently many actual arguments. Since arguments can only be omitted from the end of the actual argument list, all parameters after a parameter with a default value have to have default values as well. (Although the use of named argument notation could allow this restriction to be relaxed, it's still enforced so that positional argument notation works sensibly.) Whether or not you use it, this capability creates a need for precautions when calling functions in databases where some users mistrust other users; see \u003ca class=\"xref\" href=\"/docs/18/typeconv-func.html\" title=\"10.3. Functions\"\u003eSection 10.3\u003c/a\u003e.\u003c/p\u003e\n\u003cp\u003eFor example:\u003c/p\u003e\n\u003cpre class=\"screen\"\u003eCREATE FUNCTION foo(a int, b int DEFAULT 2, c int DEFAULT 3)\nRETURNS int\nLANGUAGE SQL\nAS $$\n    SELECT $1 + $2 + $3;\n$$;\n\nSELECT foo(10, 20, 30);\n foo\n-----\n  60\n(1 row)\n\nSELECT foo(10, 20);\n foo\n-----\n  33\n(1 row)\n\nSELECT foo(10);\n foo\n-----\n  15\n(1 row)\n\nSELECT foo();  -- fails since there is no default for the first argument\nERROR:  function foo() does not exist\n\u003c/pre\u003e\n\u003cp\u003eThe \u003ccode class=\"literal\"\u003e=\u003c/code\u003e sign can also be used in place of the key word \u003ccode class=\"literal\"\u003eDEFAULT\u003c/code\u003e.\u003c/p\u003e\n\u003c/div\u003e\n\u003cdiv class=\"sect2\" id=\"XFUNC-SQL-TABLE-FUNCTIONS\"\u003e\n\u003cdiv class=\"titlepage\"\u003e\n\u003cdiv\u003e\n\u003cdiv\u003e\n\u003ch3 class=\"title\"\u003e36.5.8. SQL Functions as Table Sources \u003c/h3\u003e\n\u003c/div\u003e\n\u003c/div\u003e\n\u003c/div\u003e\n\u003cp\u003eAll SQL functions can be used in the \u003ccode class=\"literal\"\u003eFROM\u003c/code\u003e clause of a query, but it is particularly useful for functions returning composite types. If the function is defined to return a base type, the table function produces a one-column table. If the function is defined to return a composite type, the table function produces a column for each attribute of the composite type.\u003c/p\u003e\n\u003cp\u003eHere is an example:\u003c/p\u003e\n\u003cpre class=\"screen\"\u003eCREATE TABLE foo (fooid int, foosubid int, fooname text);\nINSERT INTO foo VALUES (1, 1, 'Joe');\nINSERT INTO foo VALUES (1, 2, 'Ed');\nINSERT INTO foo VALUES (2, 1, 'Mary');\n\nCREATE FUNCTION getfoo(int) RETURNS foo AS $$\n    SELECT * FROM foo WHERE fooid = $1;\n$$ LANGUAGE SQL;\n\nSELECT *, upper(fooname) FROM getfoo(1) AS t1;\n\n fooid | foosubid | fooname | upper\n-------+----------+---------+-------\n     1 |        1 | Joe     | JOE\n(1 row)\n\u003c/pre\u003e\n\u003cp\u003eAs the example shows, we can work with the columns of the function's result just the same as if they were columns of a regular table.\u003c/p\u003e\n\u003cp\u003eNote that we only got one row out of the function. This is because we did not use \u003ccode class=\"literal\"\u003eSETOF\u003c/code\u003e. That is described in the next section.\u003c/p\u003e\n\u003c/div\u003e\n\u003cdiv class=\"sect2\" id=\"XFUNC-SQL-FUNCTIONS-RETURNING-SET\"\u003e\n\u003cdiv class=\"titlepage\"\u003e\n\u003cdiv\u003e\n\u003cdiv\u003e\n\u003ch3 class=\"title\"\u003e36.5.9. SQL Functions Returning Sets \u003c/h3\u003e\n\u003c/div\u003e\n\u003c/div\u003e\n\u003c/div\u003e\n\u003cp\u003eWhen an SQL function is declared as returning \u003ccode class=\"literal\"\u003eSETOF \u003cem class=\"replaceable\"\u003e\u003ccode\u003esometype\u003c/code\u003e\u003c/em\u003e\u003c/code\u003e, the function's final query is executed to completion, and each row it outputs is returned as an element of the result set.\u003c/p\u003e\n\u003cp\u003eThis feature is normally used when calling the function in the \u003ccode class=\"literal\"\u003eFROM\u003c/code\u003e clause. In this case each row returned by the function becomes a row of the table seen by the query. For example, assume that table \u003ccode class=\"literal\"\u003efoo\u003c/code\u003e has the same contents as above, and we say:\u003c/p\u003e\n\u003cpre class=\"programlisting\"\u003eCREATE FUNCTION getfoo(int) RETURNS SETOF foo AS $$\n    SELECT * FROM foo WHERE fooid = $1;\n$$ LANGUAGE SQL;\n\nSELECT * FROM getfoo(1) AS t1;\n\u003c/pre\u003e\n\u003cp\u003eThen we would get:\u003c/p\u003e\n\u003cpre class=\"screen\"\u003e fooid | foosubid | fooname\n-------+----------+---------\n     1 |        1 | Joe\n     1 |        2 | Ed\n(2 rows)\n\u003c/pre\u003e\n\u003cp\u003eIt is also possible to return multiple rows with the columns defined by output parameters, like this:\u003c/p\u003e\n\u003cpre class=\"programlisting\"\u003eCREATE TABLE tab (y int, z int);\nINSERT INTO tab VALUES (1, 2), (3, 4), (5, 6), (7, 8);\n\nCREATE FUNCTION sum_n_product_with_tab (x int, OUT sum int, OUT product int)\nRETURNS SETOF record\nAS $$\n    SELECT $1 + tab.y, $1 * tab.y FROM tab;\n$$ LANGUAGE SQL;\n\nSELECT * FROM sum_n_product_with_tab(10);\n sum | product\n-----+---------\n  11 |      10\n  13 |      30\n  15 |      50\n  17 |      70\n(4 rows)\n\u003c/pre\u003e\n\u003cp\u003eThe key point here is that you must write \u003ccode class=\"literal\"\u003eRETURNS SETOF record\u003c/code\u003e to indicate that the function returns multiple rows instead of just one. If there is only one output parameter, write that parameter's type instead of \u003ccode class=\"type\"\u003erecord\u003c/code\u003e.\u003c/p\u003e\n\u003cp\u003eIt is frequently useful to construct a query's result by invoking a set-returning function multiple times, with the parameters for each invocation coming from successive rows of a table or subquery. The preferred way to do this is to use the \u003ccode class=\"literal\"\u003eLATERAL\u003c/code\u003e key word, which is described in \u003ca class=\"xref\" href=\"/docs/18/queries-table-expressions.html#QUERIES-LATERAL\" title=\"7.2.1.5. LATERAL Subqueries\"\u003eSection 7.2.1.5\u003c/a\u003e. Here is an example using a set-returning function to enumerate elements of a tree structure:\u003c/p\u003e\n\u003cpre class=\"screen\"\u003eSELECT * FROM nodes;\n   name    | parent\n-----------+--------\n Top       |\n Child1    | Top\n Child2    | Top\n Child3    | Top\n SubChild1 | Child1\n SubChild2 | Child1\n(6 rows)\n\nCREATE FUNCTION listchildren(text) RETURNS SETOF text AS $$\n    SELECT name FROM nodes WHERE parent = $1\n$$ LANGUAGE SQL STABLE;\n\nSELECT * FROM listchildren('Top');\n listchildren\n--------------\n Child1\n Child2\n Child3\n(3 rows)\n\nSELECT name, child FROM nodes, LATERAL listchildren(name) AS child;\n  name  |   child\n--------+-----------\n Top    | Child1\n Top    | Child2\n Top    | Child3\n Child1 | SubChild1\n Child1 | SubChild2\n(5 rows)\n\u003c/pre\u003e\n\u003cp\u003eThis example does not do anything that we couldn't have done with a simple join, but in more complex calculations the option to put some of the work into a function can be quite convenient.\u003c/p\u003e\n\u003cp\u003eFunctions returning sets can also be called in the select list of a query. For each row that the query generates by itself, the set-returning function is invoked, and an output row is generated for each element of the function's result set. The previous example could also be done with queries like these:\u003c/p\u003e\n\u003cpre class=\"screen\"\u003eSELECT listchildren('Top');\n listchildren\n--------------\n Child1\n Child2\n Child3\n(3 rows)\n\nSELECT name, listchildren(name) FROM nodes;\n  name  | listchildren\n--------+--------------\n Top    | Child1\n Top    | Child2\n Top    | Child3\n Child1 | SubChild1\n Child1 | SubChild2\n(5 rows)\n\u003c/pre\u003e\n\u003cp\u003eIn the last \u003ccode class=\"command\"\u003eSELECT\u003c/code\u003e, notice that no output row appears for \u003ccode class=\"literal\"\u003eChild2\u003c/code\u003e, \u003ccode class=\"literal\"\u003eChild3\u003c/code\u003e, etc. This happens because \u003ccode class=\"function\"\u003elistchildren\u003c/code\u003e returns an empty set for those arguments, so no result rows are generated. This is the same behavior as we got from an inner join to the function result when using the \u003ccode class=\"literal\"\u003eLATERAL\u003c/code\u003e syntax.\u003c/p\u003e\n\u003cp\u003e\u003cspan class=\"productname\"\u003ePostgreSQL\u003c/span\u003e's behavior for a set-returning function in a query's select list is almost exactly the same as if the set-returning function had been written in a \u003ccode class=\"literal\"\u003eLATERAL FROM\u003c/code\u003e-clause item instead. For example,\u003c/p\u003e\n\u003cpre class=\"programlisting\"\u003eSELECT x, generate_series(1,5) AS g FROM tab;\n\u003c/pre\u003e\n\u003cp\u003eis almost equivalent to\u003c/p\u003e\n\u003cpre class=\"programlisting\"\u003eSELECT x, g FROM tab, LATERAL generate_series(1,5) AS g;\n\u003c/pre\u003e\n\u003cp\u003eIt would be exactly the same, except that in this specific example, the planner could choose to put \u003ccode class=\"structname\"\u003eg\u003c/code\u003e on the outside of the nested-loop join, since \u003ccode class=\"structname\"\u003eg\u003c/code\u003e has no actual lateral dependency on \u003ccode class=\"structname\"\u003etab\u003c/code\u003e. That would result in a different output row order. Set-returning functions in the select list are always evaluated as though they are on the inside of a nested-loop join with the rest of the \u003ccode class=\"literal\"\u003eFROM\u003c/code\u003e clause, so that the function(s) are run to completion before the next row from the \u003ccode class=\"literal\"\u003eFROM\u003c/code\u003e clause is considered.\u003c/p\u003e\n\u003cp\u003eIf there is more than one set-returning function in the query's select list, the behavior is similar to what you get from putting the functions into a single \u003ccode class=\"literal\"\u003eLATERAL ROWS FROM( ... )\u003c/code\u003e \u003ccode class=\"literal\"\u003eFROM\u003c/code\u003e-clause item. For each row from the underlying query, there is an output row using the first result from each function, then an output row using the second result, and so on. If some of the set-returning functions produce fewer outputs than others, null values are substituted for the missing data, so that the total number of rows emitted for one underlying row is the same as for the set-returning function that produced the most outputs. Thus the set-returning functions run \u003cspan class=\"quote\"\u003e“\u003cspan class=\"quote\"\u003ein lockstep\u003c/span\u003e”\u003c/span\u003e until they are all exhausted, and then execution continues with the next underlying row.\u003c/p\u003e\n\u003cp\u003eSet-returning functions can be nested in a select list, although that is not allowed in \u003ccode class=\"literal\"\u003eFROM\u003c/code\u003e-clause items. In such cases, each level of nesting is treated separately, as though it were a separate \u003ccode class=\"literal\"\u003eLATERAL ROWS FROM( ... )\u003c/code\u003e item. For example, in\u003c/p\u003e\n\u003cpre class=\"programlisting\"\u003eSELECT srf1(srf2(x), srf3(y)), srf4(srf5(z)) FROM tab;\n\u003c/pre\u003e\n\u003cp\u003ethe set-returning functions \u003ccode class=\"function\"\u003esrf2\u003c/code\u003e, \u003ccode class=\"function\"\u003esrf3\u003c/code\u003e, and \u003ccode class=\"function\"\u003esrf5\u003c/code\u003e would be run in lockstep for each row of \u003ccode class=\"structname\"\u003etab\u003c/code\u003e, and then \u003ccode class=\"function\"\u003esrf1\u003c/code\u003e and \u003ccode class=\"function\"\u003esrf4\u003c/code\u003e would be applied in lockstep to each row produced by the lower functions.\u003c/p\u003e\n\u003cp\u003eSet-returning functions cannot be used within conditional-evaluation constructs, such as \u003ccode class=\"literal\"\u003eCASE\u003c/code\u003e or \u003ccode class=\"literal\"\u003eCOALESCE\u003c/code\u003e. For example, consider\u003c/p\u003e\n\u003cpre class=\"programlisting\"\u003eSELECT x, CASE WHEN x \u0026gt; 0 THEN generate_series(1, 5) ELSE 0 END FROM tab;\n\u003c/pre\u003e\n\u003cp\u003eIt might seem that this should produce five repetitions of input rows that have \u003ccode class=\"literal\"\u003ex \u0026gt; 0\u003c/code\u003e, and a single repetition of those that do not; but actually, because \u003ccode class=\"function\"\u003egenerate_series(1, 5)\u003c/code\u003e would be run in an implicit \u003ccode class=\"literal\"\u003eLATERAL FROM\u003c/code\u003e item before the \u003ccode class=\"literal\"\u003eCASE\u003c/code\u003e expression is ever evaluated, it would produce five repetitions of every input row. To reduce confusion, such cases produce a parse-time error instead.\u003c/p\u003e\n\u003cdiv class=\"note\"\u003e\n\u003ch3 class=\"title\"\u003eNote\u003c/h3\u003e\n\u003cp\u003eIf a function's last command is \u003ccode class=\"command\"\u003eINSERT\u003c/code\u003e, \u003ccode class=\"command\"\u003eUPDATE\u003c/code\u003e, \u003ccode class=\"command\"\u003eDELETE\u003c/code\u003e, or \u003ccode class=\"command\"\u003eMERGE\u003c/code\u003e with \u003ccode class=\"literal\"\u003eRETURNING\u003c/code\u003e, that command will always be executed to completion, even if the function is not declared with \u003ccode class=\"literal\"\u003eSETOF\u003c/code\u003e or the calling query does not fetch all the result rows. Any extra rows produced by the \u003ccode class=\"literal\"\u003eRETURNING\u003c/code\u003e clause are silently dropped, but the commanded table modifications still happen (and are all completed before returning from the function).\u003c/p\u003e\n\u003c/div\u003e\n\u003cdiv class=\"note\"\u003e\n\u003ch3 class=\"title\"\u003eNote\u003c/h3\u003e\n\u003cp\u003eBefore \u003cspan class=\"productname\"\u003ePostgreSQL\u003c/span\u003e 10, putting more than one set-returning function in the same select list did not behave very sensibly unless they always produced equal numbers of rows. Otherwise, what you got was a number of output rows equal to the least common multiple of the numbers of rows produced by the set-returning functions. Also, nested set-returning functions did not work as described above; instead, a set-returning function could have at most one set-returning argument, and each nest of set-returning functions was run independently. Also, conditional execution (set-returning functions inside \u003ccode class=\"literal\"\u003eCASE\u003c/code\u003e etc.) was previously allowed, complicating things even more. Use of the \u003ccode class=\"literal\"\u003eLATERAL\u003c/code\u003e syntax is recommended when writing queries that need to work in older \u003cspan class=\"productname\"\u003ePostgreSQL\u003c/span\u003e versions, because that will give consistent results across different versions. If you have a query that is relying on conditional execution of a set-returning function, you may be able to fix it by moving the conditional test into a custom set-returning function. For example,\u003c/p\u003e\n\u003cpre class=\"programlisting\"\u003eSELECT x, CASE WHEN y \u0026gt; 0 THEN generate_series(1, z) ELSE 5 END FROM tab;\n\u003c/pre\u003e\n\u003cp\u003ecould become\u003c/p\u003e\n\u003cpre class=\"programlisting\"\u003eCREATE FUNCTION case_generate_series(cond bool, start int, fin int, els int)\n  RETURNS SETOF int AS $$\nBEGIN\n  IF cond THEN\n    RETURN QUERY SELECT generate_series(start, fin);\n  ELSE\n    RETURN QUERY SELECT els;\n  END IF;\nEND$$ LANGUAGE plpgsql;\n\nSELECT x, case_generate_series(y \u0026gt; 0, 1, z, 5) FROM tab;\n\u003c/pre\u003e\n\u003cp\u003eThis formulation will work the same in all versions of \u003cspan class=\"productname\"\u003ePostgreSQL\u003c/span\u003e.\u003c/p\u003e\n\u003c/div\u003e\n\u003c/div\u003e\n\u003cdiv class=\"sect2\" id=\"XFUNC-SQL-FUNCTIONS-RETURNING-TABLE\"\u003e\n\u003cdiv class=\"titlepage\"\u003e\n\u003cdiv\u003e\n\u003cdiv\u003e\n\u003ch3 class=\"title\"\u003e36.5.10. SQL Functions Returning \u003ccode class=\"literal\"\u003eTABLE\u003c/code\u003e \u003c/h3\u003e\n\u003c/div\u003e\n\u003c/div\u003e\n\u003c/div\u003e\n\u003cp\u003eThere is another way to declare a function as returning a set, which is to use the syntax \u003ccode class=\"literal\"\u003eRETURNS TABLE(\u003cem class=\"replaceable\"\u003e\u003ccode\u003ecolumns\u003c/code\u003e\u003c/em\u003e)\u003c/code\u003e. This is equivalent to using one or more \u003ccode class=\"literal\"\u003eOUT\u003c/code\u003e parameters plus marking the function as returning \u003ccode class=\"literal\"\u003eSETOF record\u003c/code\u003e (or \u003ccode class=\"literal\"\u003eSETOF\u003c/code\u003e a single output parameter's type, as appropriate). This notation is specified in recent versions of the SQL standard, and thus may be more portable than using \u003ccode class=\"literal\"\u003eSETOF\u003c/code\u003e.\u003c/p\u003e\n\u003cp\u003eFor example, the preceding sum-and-product example could also be done this way:\u003c/p\u003e\n\u003cpre class=\"programlisting\"\u003eCREATE FUNCTION sum_n_product_with_tab (x int)\nRETURNS TABLE(sum int, product int) AS $$\n    SELECT $1 + tab.y, $1 * tab.y FROM tab;\n$$ LANGUAGE SQL;\n\u003c/pre\u003e\n\u003cp\u003eIt is not allowed to use explicit \u003ccode class=\"literal\"\u003eOUT\u003c/code\u003e or \u003ccode class=\"literal\"\u003eINOUT\u003c/code\u003e parameters with the \u003ccode class=\"literal\"\u003eRETURNS TABLE\u003c/code\u003e notation — you must put all the output columns in the \u003ccode class=\"literal\"\u003eTABLE\u003c/code\u003e list.\u003c/p\u003e\n\u003c/div\u003e\n\u003cdiv class=\"sect2\" id=\"XFUNC-SQL-POLYMORPHIC-FUNCTIONS\"\u003e\n\u003cdiv class=\"titlepage\"\u003e\n\u003cdiv\u003e\n\u003cdiv\u003e\n\u003ch3 class=\"title\"\u003e36.5.11. Polymorphic SQL Functions \u003c/h3\u003e\n\u003c/div\u003e\n\u003c/div\u003e\n\u003c/div\u003e\n\u003cp\u003eSQL functions can be declared to accept and return the polymorphic types described in \u003ca class=\"xref\" href=\"/docs/18/extend-type-system.html#EXTEND-TYPES-POLYMORPHIC\" title=\"36.2.5. Polymorphic Types\"\u003eSection 36.2.5\u003c/a\u003e. Here is a polymorphic function \u003ccode class=\"function\"\u003emake_array\u003c/code\u003e that builds up an array from two arbitrary data type elements:\u003c/p\u003e\n\u003cpre class=\"screen\"\u003eCREATE FUNCTION make_array(anyelement, anyelement) RETURNS anyarray AS $$\n    SELECT ARRAY[$1, $2];\n$$ LANGUAGE SQL;\n\nSELECT make_array(1, 2) AS intarray, make_array('a'::text, 'b') AS textarray;\n intarray | textarray\n----------+-----------\n {1,2}    | {a,b}\n(1 row)\n\u003c/pre\u003e\n\u003cp\u003eNotice the use of the typecast \u003ccode class=\"literal\"\u003e'a'::text\u003c/code\u003e to specify that the argument is of type \u003ccode class=\"type\"\u003etext\u003c/code\u003e. This is required if the argument is just a string literal, since otherwise it would be treated as type \u003ccode class=\"type\"\u003eunknown\u003c/code\u003e, and array of \u003ccode class=\"type\"\u003eunknown\u003c/code\u003e is not a valid type. Without the typecast, you will get errors like this:\u003c/p\u003e\n\u003cpre class=\"screen\"\u003eERROR:  could not determine polymorphic type because input has type unknown\n\u003c/pre\u003e\n\u003cp\u003eWith \u003ccode class=\"function\"\u003emake_array\u003c/code\u003e declared as above, you must provide two arguments that are of exactly the same data type; the system will not attempt to resolve any type differences. Thus for example this does not work:\u003c/p\u003e\n\u003cpre class=\"screen\"\u003eSELECT make_array(1, 2.5) AS numericarray;\nERROR:  function make_array(integer, numeric) does not exist\n\u003c/pre\u003e\n\u003cp\u003eAn alternative approach is to use the \u003cspan class=\"quote\"\u003e“\u003cspan class=\"quote\"\u003ecommon\u003c/span\u003e”\u003c/span\u003e family of polymorphic types, which allows the system to try to identify a suitable common type:\u003c/p\u003e\n\u003cpre class=\"screen\"\u003eCREATE FUNCTION make_array2(anycompatible, anycompatible)\nRETURNS anycompatiblearray AS $$\n    SELECT ARRAY[$1, $2];\n$$ LANGUAGE SQL;\n\nSELECT make_array2(1, 2.5) AS numericarray;\n numericarray\n--------------\n {1,2.5}\n(1 row)\n\u003c/pre\u003e\n\u003cp\u003eBecause the rules for common type resolution default to choosing type \u003ccode class=\"type\"\u003etext\u003c/code\u003e when all inputs are of unknown types, this also works:\u003c/p\u003e\n\u003cpre class=\"screen\"\u003eSELECT make_array2('a', 'b') AS textarray;\n textarray\n-----------\n {a,b}\n(1 row)\n\u003c/pre\u003e\n\u003cp\u003eIt is permitted to have polymorphic arguments with a fixed return type, but the converse is not. For example:\u003c/p\u003e\n\u003cpre class=\"screen\"\u003eCREATE FUNCTION is_greater(anyelement, anyelement) RETURNS boolean AS $$\n    SELECT $1 \u0026gt; $2;\n$$ LANGUAGE SQL;\n\nSELECT is_greater(1, 2);\n is_greater\n------------\n f\n(1 row)\n\nCREATE FUNCTION invalid_func() RETURNS anyelement AS $$\n    SELECT 1;\n$$ LANGUAGE SQL;\nERROR:  cannot determine result data type\nDETAIL:  A result of type anyelement requires at least one input of type anyelement, anyarray, anynonarray, anyenum, or anyrange.\n\u003c/pre\u003e\n\u003cp\u003ePolymorphism can be used with functions that have output arguments. For example:\u003c/p\u003e\n\u003cpre class=\"screen\"\u003eCREATE FUNCTION dup (f1 anyelement, OUT f2 anyelement, OUT f3 anyarray)\nAS 'select $1, array[$1,$1]' LANGUAGE SQL;\n\nSELECT * FROM dup(22);\n f2 |   f3\n----+---------\n 22 | {22,22}\n(1 row)\n\u003c/pre\u003e\n\u003cp\u003ePolymorphism can also be used with variadic functions. For example:\u003c/p\u003e\n\u003cpre class=\"screen\"\u003eCREATE FUNCTION anyleast (VARIADIC anyarray) RETURNS anyelement AS $$\n    SELECT min($1[i]) FROM generate_subscripts($1, 1) g(i);\n$$ LANGUAGE SQL;\n\nSELECT anyleast(10, -1, 5, 4);\n anyleast\n----------\n       -1\n(1 row)\n\nSELECT anyleast('abc'::text, 'def');\n anyleast\n----------\n abc\n(1 row)\n\nCREATE FUNCTION concat_values(text, VARIADIC anyarray) RETURNS text AS $$\n    SELECT array_to_string($2, $1);\n$$ LANGUAGE SQL;\n\nSELECT concat_values('|', 1, 4, 2);\n concat_values\n---------------\n 1|4|2\n(1 row)\n\u003c/pre\u003e\n\u003c/div\u003e\n\u003cdiv class=\"sect2\" id=\"XFUNC-SQL-COLLATIONS\"\u003e\n\u003cdiv class=\"titlepage\"\u003e\n\u003cdiv\u003e\n\u003cdiv\u003e\n\u003ch3 class=\"title\"\u003e36.5.12. SQL Functions with Collations \u003c/h3\u003e\n\u003c/div\u003e\n\u003c/div\u003e\n\u003c/div\u003e\n\u003cp\u003eWhen an SQL function has one or more parameters of collatable data types, a collation is identified for each function call depending on the collations assigned to the actual arguments, as described in \u003ca class=\"xref\" href=\"/docs/18/collation.html\" title=\"23.2. Collation Support\"\u003eSection 23.2\u003c/a\u003e. If a collation is successfully identified (i.e., there are no conflicts of implicit collations among the arguments) then all the collatable parameters are treated as having that collation implicitly. This will affect the behavior of collation-sensitive operations within the function. For example, using the \u003ccode class=\"function\"\u003eanyleast\u003c/code\u003e function described above, the result of\u003c/p\u003e\n\u003cpre class=\"programlisting\"\u003eSELECT anyleast('abc'::text, 'ABC');\n\u003c/pre\u003e\n\u003cp\u003ewill depend on the database's default collation. In \u003ccode class=\"literal\"\u003eC\u003c/code\u003e locale the result will be \u003ccode class=\"literal\"\u003eABC\u003c/code\u003e, but in many other locales it will be \u003ccode class=\"literal\"\u003eabc\u003c/code\u003e. The collation to use can be forced by adding a \u003ccode class=\"literal\"\u003eCOLLATE\u003c/code\u003e clause to any of the arguments, for example\u003c/p\u003e\n\u003cpre class=\"programlisting\"\u003eSELECT anyleast('abc'::text, 'ABC' COLLATE \"C\");\n\u003c/pre\u003e\n\u003cp\u003eAlternatively, if you wish a function to operate with a particular collation regardless of what it is called with, insert \u003ccode class=\"literal\"\u003eCOLLATE\u003c/code\u003e clauses as needed in the function definition. This version of \u003ccode class=\"function\"\u003eanyleast\u003c/code\u003e would always use \u003ccode class=\"literal\"\u003een_US\u003c/code\u003e locale to compare strings:\u003c/p\u003e\n\u003cpre class=\"programlisting\"\u003eCREATE FUNCTION anyleast (VARIADIC anyarray) RETURNS anyelement AS $$\n    SELECT min($1[i] COLLATE \"en_US\") FROM generate_subscripts($1, 1) g(i);\n$$ LANGUAGE SQL;\n\u003c/pre\u003e\n\u003cp\u003eBut note that this will throw an error if applied to a non-collatable data type.\u003c/p\u003e\n\u003cp\u003eIf no common collation can be identified among the actual arguments, then an SQL function treats its parameters as having their data types' default collation (which is usually the database's default collation, but could be different for parameters of domain types).\u003c/p\u003e\n\u003cp\u003eThe behavior of collatable parameters can be thought of as a limited form of polymorphism, applicable only to textual data types.\u003c/p\u003e\n\u003c/div\u003e\n\u003c/div\u003e","related":[],"sections":[],"tables":[]}},"RequestedLocale":"zh-Hans","Fallback":true,"Versions":["10","11","12","13","14","15","16","17","18","19","20"],"Locales":["en"],"Signatures":null,"Spellings":null,"SQLState":null,"Evidence":null}
