1

I have a very simple example for the summation of two numbers.

CREATE OR REPLACE FUNCTION add(a integer, b integer) RETURNS integer AS
$$
  SELECT $1+$2;
$$ LANGUAGE 'sql';

My question is how to define a range b 10:20, whose values will counted up by one until the end of the range (20) is reached.

The result hast to be like this

res = a + b
res = a + 10
res = a + 11
res = a + 12
res = a + 13

When I retrieve the function add with:

SELECT add(1);

there should be the results: 11,12,13,...,21.

I didn't use loops like FOR EACH before (especially in the LANGUAGE sql).

Is it better to write those functions in plpgsql?

0

3 Answers 3

2

I didn't use loops like FOR EACH before (especially in the LANGUAGE sql).

There are no loops in SQL. (The only exception being RECURSIVE CTEs.) Functions with LANGUAGE sql (no quotes!), consist of SQL statements exclusively. If you need procedural elements like loops, you need to switch to PL/pgSQL (or any other procedural language) where looping is easy enough.

Of course, the simple example you presented would best be solved with generate_series(), as other answers already pointed out.

A word of caution: best use generate_series() in the FROM list. Using it in the SELECT list is allowed but frowned upon because non-standard. SRF (set returning functions) might be confined to the FROM list in future releases.

Sign up to request clarification or add additional context in comments.

Comments

2

I think you are looking for the function generate_series(), documented here.

So,

select generate_series(1, 3)

Will return three rows:

1
2
3

You can use these numbers in arithmetic expressions.

Comments

0
select add(1, b)
from generate_series(10, 20) b

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.