2

I would like to understand why the code below isn't working. I am using postgres 13, it is saying "syntax error near nu int[]" underlining int. I am trying to get started with array manipulation.

DECLARE
    num int[] := '{1, 2, 3, 4, 5}';
    s int := 0;
    x int;
BEGIN
    
    FOR x IN 1..5 LOOP
        s:= s + num[x];
    END LOOP;
END;
1
  • 4
    You need to use a DO block to run procedural (PL/pgSQL) code. Commented Apr 14, 2021 at 9:12

1 Answer 1

2

Welcome to SO.

You forgot to specify in your code that you're not using SQL. To use PL/pgSQL code you either need to use a function / procedure or an anonymous code block:

DO $$ 
DECLARE
    num int[] := '{1, 2, 3, 4, 5}';
    s int := 0;
    x int;
BEGIN 
    FOR x IN 1..5 LOOP
        s:= s + num[x];
        RAISE NOTICE '%',s;  -- See the output in the console
    END LOOP;
END; $$

NOTICE:  1
NOTICE:  3
NOTICE:  6
NOTICE:  10
NOTICE:  15
Sign up to request clarification or add additional context in comments.

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.