Italo Lemos
Italo Lemos

Reputation: 1022

How to create a function with postgres

I'm trying to run this command according the documentation but it always returns 1, i.e. not the number of rows that I want

CREATE FUNCTION getQuantity() RETURNS integer $$
   select count(*) from table;
$$ LANGUAGE SQL;

select getQuantity();

Does anyone know if I'm doing something wrong?

Upvotes: 0

Views: 685

Answers (1)

klin
klin

Reputation: 121474

You missed a keyword as. Also, count(*) returns bigint, so:

create function get_quantity() 
returns bigint as $$
   select count(*) from my_table;
$$ language sql;

or

create function get_quantity() 
returns integer as $$
   select count(*)::int from my_table;
$$ language sql;

Test it in dbfiddle.

Upvotes: 1

Related Questions