CodeBlanks Logo Icon CodeBlanks

CREATE FUNCTION

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

query.sql
-- write function
CREATE

Sample solution

query.sql
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

Question
CREATE FUNCTION full_name(first VARCHAR, last VARCHAR)
____ VARCHAR
Answer
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

All lessons in Advanced