Extending the Database: SQL Functions

* SQL functions are group of SQL statements which return the last statement, which should be a SELECT one.

* Example:

test=> CREATE FUNCTION name_len(employees)
test-> RETURNS int4
test-> AS
test-> 'SELECT
test'> CASE WHEN $1.last_name = null THEN 0 ELSE char_length($1.last_name) END
test'> + 1 +
test'> CASE WHEN $1.last_name = null THEN 0 ELSE char_length($1.last_name) END
test'> AS name_length'
test-> LANGUAGE 'sql' \g
CREATE

* Now you can use this function inside your queries:

test=> SELECT name_len(employees)
test-> FROM employees \g