ClickHouse/docs/en/sql-reference/statements/create/function.md

59 lines
1.7 KiB
Markdown
Raw Normal View History

2021-08-21 12:38:19 +00:00
---
toc_priority: 38
toc_title: FUNCTION
---
# CREATE FUNCTION {#create-function}
Creates a user defined function from a lambda expression. The expression must consist of function parameters, constants, operators or other function calls.
2021-08-21 12:38:19 +00:00
**Syntax**
```sql
CREATE FUNCTION name AS (parameter0, ...) -> expression
2021-08-21 12:38:19 +00:00
```
A function can have an arbitrary number of parameters.
There are a few restrictions:
2021-08-21 12:38:19 +00:00
- The name of a function must be unique among user defined and system functions.
- Recursive functions are not allowed.
- All variables used by a function must be specified in its parameter list.
2021-08-21 12:38:19 +00:00
If any restriction is violated then an exception is raised.
2021-08-21 12:38:19 +00:00
**Example**
Query:
```sql
CREATE FUNCTION linear_equation AS (x, k, b) -> k*x + b;
SELECT number, linear_equation(number, 2, 1) FROM numbers(3);
2021-08-21 12:38:19 +00:00
```
Result:
``` text
┌─number─┬─linear_equation(number, 2, 1)─┐
│ 0 │ 1 │
│ 1 │ 3 │
│ 2 │ 5 │
└────────┴───────────────────────────────┘
```
A [conditional function](../../../sql-reference/functions/conditional-functions.md) is called in a user defined function in the following query:
```sql
CREATE FUNCTION parity AS (n) -> if(number % 2, 'odd', 'even');
SELECT number, parity(number) FROM numbers(3);
2021-08-21 12:38:19 +00:00
```
Result:
``` text
┌─number─┬─parity(number)─┐
│ 0 │ even │
│ 1 │ odd │
│ 2 │ even │
└────────┴────────────────┘
```