CREATE FUNCTION
- SQL course
- Advanced
- Lesson 43/81
- 4 min
Define a function.
CREATE FUNCTION
With CREATE FUNCTION you define SQL code that returns a value.
CREATE FUNCTION full_name(first VARCHAR, last VARCHAR)
RETURNS VARCHAR
LANGUAGE SQL
AS $$
SELECT first || ' ' || last;
$$;This query combines first and last name.
The function full_name is created. The expression first || ' ' || last is evaluated and returned.
CREATE FUNCTION — details
A function specifies its return type with RETURNS. The body goes between AS $$.
For example, RETURNS DECIMAL states that the function returns a decimal number; if the value doesn't fit that type the database raises an error.
Practice CREATE FUNCTION
Create a full_name function: combine first and last name.
Starter code
-- write function
CREATESample solution
CREATE FUNCTION full_name(first VARCHAR, last VARCHAR)
RETURNS VARCHAR
LANGUAGE SQL
AS $$
SELECT first || ' ' || last;
$$;Expected output
Function oluşturuldu
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Add RETURNS
CREATE FUNCTION full_name(first VARCHAR, last VARCHAR)
____ VARCHAR
CREATE FUNCTION full_name(first VARCHAR, last VARCHAR)
RETURNS VARCHAR
Explanation: RETURNS is the right answer.
2 What specifies a function's return type?
- RETURN
- AS
- RETURNS Correct answer
- IN
Explanation: RETURNS specifies the return type.
3 CREATE FUNCTION: match the terms
| Term | Meaning |
|---|---|
CREATE FUNCTION |
create |
RETURNS |
return type |
AS |
body |
|| |
concatenate |