PostgreSQL Create Function

PostgreSQL Create Function

The PostgreSQL CREATE FUNCTION is used to create a function in a PostgreSQL database.

Create Function example

CREATE OR REPLACE FUNCTION
change_price(in p_name varchar(50), in p_price numeric) 
RETURNS varchar AS $$
DECLARE
  v_msg varchar(250):='Price changed';
  v_count numeric:=0;
BEGIN
  SELECT count(*) into v_count 
  FROM goods 
  WHERE name = p_name;
  if v_count=0 then
    v_msg:='No name found';
    return v_msg;
  else
    update goods 
	set price=p_price 
	where name = p_name;
    return v_msg;
  end if;   
EXCEPTION 
  when others then
    begin
     v_msg := 'Error!';
     return v_msg;
    end;    
END;
$$ LANGUAGE 'plpgsql';