CodeBlanks Logo Icon CodeBlanks

RETURN

Return a value.

RETURN

RETURN sends a value back from a function. Written at the end of the body.

CREATE FUNCTION square(n INT)
RETURNS INT
LANGUAGE SQL
AS $$
  SELECT n * n;
$$;

This query returns the square of n.

The function square is created. The expression n * n is evaluated and returned.

RETURN — details

In SQL functions the last SELECT is returned automatically. PL/pgSQL uses RETURN.

LANGUAGE SQL functions are short because they are a single query; if you need IF or loops you write a PL/pgSQL function and return the value with RETURN.

Practice RETURN

Create a square function: return SELECT n * n.

Starter code

query.sql
-- square function
CREATE FUNCTION square

Sample solution

query.sql
CREATE FUNCTION square(n INT)
RETURNS INT
LANGUAGE SQL
AS $$
  SELECT n * n;
$$;

Expected output

Function oluşturuldu

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 RETURN: match the terms

Term Meaning
RETURN return
last SELECT automatic
body AS
value result

2 Add n * n

Question
  SELECT ____
Answer
  SELECT n * n

Explanation: The function returns the result of its last SELECT; n * n computes the square.

3 What does an SQL function return?

  • The first SELECT
  • RETURN
  • None
  • The last SELECT Correct answer

Explanation: An SQL function returns the last SELECT.

All lessons in Advanced