How to pass custom type array to Postgres function

You can use the alternative syntax with a array literal instead of the array constructor, which is a Postgres function-like construct and may cause trouble when you need to pass values – like in a prepared statement: SELECT myschema.myfunc(‘0d6311cc-0d74-4a32-8cf9-87835651e1ee’ , ‘{“(0d6311cc-0d74-4a32-8cf9-87835651e1ee, 25)” , “(6449fb3b-844e-440e-8973-31eb6bbefc81, 10)”}’::mytype[]); I added a line break between the two row types … Read more

Window Functions or Common Table Expressions: count previous rows within range

I don’t think you can do this cheaply with a plain query, CTEs and window functions – their frame definition is static, but you need a dynamic frame (depending on column values). Generally, you’ll have to define lower and upper bound of your window carefully: The following queries exclude the current row and include the … Read more

Postgres Dynamic Query Function

You cannot use a variable in place of an identifier like that. You need to do it with dynamic queries. It will look something like this: EXECUTE ‘SELECT * FROM ‘ || quote_ident(tname) || ‘ WHERE ‘ || quote_ident(cname) || ‘ NOT IN (”AK”,”CK”);’ INTO result_var; If you are using PostgreSQL 9.1 or above, you … Read more

Can I make a plpgsql function return an integer without using a variable?

Yes you can. There are a number of ways. 1) RETURN (SELECT …) CREATE OR REPLACE FUNCTION get_1(_param_id integer) RETURNS integer LANGUAGE plpgsql AS $func$ BEGIN RETURN _param_id; — Or: — RETURN (SELECT col1 FROM tbl WHERE id = _param_id); END $func$; 2) Use an OUT or INOUT parameter CREATE OR REPLACE FUNCTION get_2(_param_id integer, … Read more

Record returned from function has columns concatenated

Generally, to decompose rows returned from a function and get individual columns: SELECT * FROM account_servicetier_for_day(20424, ‘2014-08-12’); As for the query: Postgres 9.3 or newer Cleaner with JOIN LATERAL: SELECT ‘2014-08-12’ AS day, 0 AS inbytes, 0 AS outbytes , a.username, a.accountid, a.userid , f.* — but avoid duplicate column names! FROM account_tab a , … Read more

Store query result in a variable using in PL/pgSQL

I think you’re looking for SELECT select_expressions INTO: select test_table.name into name from test_table where id = x; That will pull the name from test_table where id is your function’s argument and leave it in the name variable. Don’t leave out the table name prefix on test_table.name or you’ll get complaints about an ambiguous reference.