PostgreSQL 8.0.1 Documentation | ||||
---|---|---|---|---|
Prev | Fast Backward | Chapter 31. Extending SQL | Fast Forward | Next |
31.4. Query Language (SQL) Functions
SQL 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 "the first row" of a multirow result is not well-defined unless you use ORDER BY.) If the last query happens to return no rows at all, the null value will be returned.
Alternatively, an SQL function may be declared to return a set, by specifying the function's return type as SETOF sometype. In this case all rows of the last query's result are returned. Further details appear below.
The 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 void, the last statement must be a SELECT.
Any collection of commands in the SQL language can be packaged together and defined as a function. Besides SELECT queries, the commands can include data modification queries (INSERT, UPDATE, and DELETE), as well as other SQL commands. (The only exception is that you can't put BEGIN, COMMIT, ROLLBACK, or SAVEPOINT commands into a SQL function.) However, the final command must be a SELECT that returns whatever is specified as the function's return type. Alternatively, if you want to define a SQL function that performs actions but has no useful value to return, you can define it as returning void. In that case, the function body must not end with a SELECT. For example, this function removes rows with negative salaries from the emp table:
The syntax of the CREATE FUNCTION command requires the function body to be written as a string constant. It is usually most convenient to use dollar quoting (see Section 4.1.2.2) for the string constant. If you choose to use regular single-quoted string constant syntax, you must escape single quote marks (') and backslashes (\) used in the body of the function, typically by doubling them (see Section 4.1.2.1).
Arguments to the SQL function are referenced in the function body using the syntax $n: $1 refers to the first argument, $2 to the second, and so on. If an argument is of a composite type, then the dot notation, e.g., $1.name, may be used to access attributes of the argument. The arguments can only be used as data values, not as identifiers. Thus for example this is reasonable:
but this will not work:
31.4.1. SQL Functions on Base Types
The simplest possible SQL function has no arguments and simply returns a base type, such as integer:
Notice that we defined a column alias within the function body for the result of the function (with the name result), but this column alias is not visible outside the function. Hence, the result is labeled one instead of result.
It is almost as easy to define SQL functions that take base types as arguments. In the example below, notice how we refer to the arguments within the function as $1 and $2.
Here is a more useful function, which might be used to debit a bank account:
A user could execute this function to debit account 17 by $100.00 as follows:
In practice one would probably like a more useful result from the function than a constant 1, so a more likely definition is
which adjusts the balance and returns the new balance.
31.4.2. SQL Functions on Composite Types
When writing functions with arguments of composite types, we must not only specify which argument we want (as we did above with $1 and $2) but also the desired attribute (field) of that argument. For example, suppose that emp 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 double_salary
that computes what someone's salary would be if it were doubled:
Notice the use of the syntax $1.salary to select one field of the argument row value. Also notice how the calling SELECT command uses * 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:
but this usage is deprecated since it's easy to get confused.
Sometimes it is handy to construct a composite argument value on-the-fly. This can be done with the ROW construct. For example, we could adjust the data being passed to the function:
It is also possible to build a function that returns a composite type. This is an example of a function that returns a single emp row:
In this example we have specified each of the attributes with a constant value, but any computation could have been substituted for these constants.
Note two important things about defining the function:
The select list order in the query must be exactly the same as that in which the columns appear in the table associated with the composite type. (Naming the columns, as we did above, is irrelevant to the system.)
You must typecast the expressions to match the definition of the composite type, or you will get errors like this:
ERROR: function declared to return emp returns varchar instead of text at column 1
A different way to define the same function is:
Here we wrote a SELECT 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.
We could call this function directly in either of two ways:
The second way is described more fully in Section 31.4.3.
When 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:
The extra parentheses are needed to keep the parser from getting confused. If you try to do it without them, you get something like this:
Another option is to use functional notation for extracting an attribute. The simple way to explain this is that we can use the notations attribute(table) and table.attribute interchangeably.
Tip: The equivalence between functional notation and attribute notation makes it possible to use functions on composite types to emulate "computed fields". For example, using the previous definition for double_salary(emp), we can write
SELECT emp.name, emp.double_salary FROM emp; An application using this wouldn't need to be directly aware that double_salary isn't a real column of the table. (You can also emulate computed fields with views.)
Another way to use a function returning a row result is to pass the result to another function that accepts the correct row type as input:
Another way to use a function that returns a composite type is to call it as a table function, as described below.
31.4.3. SQL Functions as Table Sources
All SQL functions may be used in the FROM 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.
Here is an example:
As 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.
Note that we only got one row out of the function. This is because we did not use SETOF. That is described in the next section.
31.4.4. SQL Functions Returning Sets
When an SQL function is declared as returning SETOF sometype, the function's final SELECT query is executed to completion, and each row it outputs is returned as an element of the result set.
This feature is normally used when calling the function in the FROM 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 foo has the same contents as above, and we say:
Then we would get:
Currently, functions returning sets may also be called in the select list of a query. For each row that the query generates by itself, the function returning set is invoked, and an output row is generated for each element of the function's result set. Note, however, that this capability is deprecated and may be removed in future releases. The following is an example function returning a set from the select list:
In the last SELECT, notice that no output row appears for Child2, Child3, etc. This happens because listchildren
returns an empty set for those arguments, so no result rows are generated.
31.4.5. Polymorphic SQL Functions
SQL functions may be declared to accept and return the polymorphic types anyelement and anyarray. See Section 31.2.5 for a more detailed explanation of polymorphic functions. Here is a polymorphic function make_array
that builds up an array from two arbitrary data type elements:
Notice the use of the typecast 'a'::text to specify that the argument is of type text. This is required if the argument is just a string literal, since otherwise it would be treated as type unknown, and array of unknown is not a valid type. Without the typecast, you will get errors like this:
It is permitted to have polymorphic arguments with a fixed return type, but the converse is not. For example: