Array declaration and manipulation in postgresql

Viewed 111

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 Answers

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
Related