I am currently learning postgresql and have a noob question. If I have a simple table like this:
CREATE TABLE rectangle
(
width int,
length int
);
And a function like this:
CREATE OR REPLACE FUNCTION Area()
RETURNS int AS $area$
declare
area int;
BEGIN
SELECT (width*length) into area FROM rectangle;
return area ;
END;
$area$ LANGUAGE plpgsql;
And I call it like this:
select width, length, area() from rectangle;
I get results like this:
width | length | area
-------------------------
2 | 3 | 6
4 | 3 | 6
5 | 2 | 6
Which shows that the area function is working but it is only using the first entry in the table and not the corresponding row. What am I doing wrong. Thanks in advance!
Not true.The function is independent of the row, and you must "pass" values from the row into that function. While this is probably just a simple example, you don't need to use a function for this and you should just use (width*length) directly in the querypkfor the function and add aWHEREselect width,length,(length*width) as area from rectangle>> ?? this is not a good situation to implement aFunctionnot really,the sample functions below both "abstract" the area calculation from any physical implementation of length or width, so the function could be used in any relevant situation. If you base a function on a PK then the function can only be used in one situation. Also note that in the sample functions below they do not need to useselect, because you pass the length and the width which have already been selected. Passing a pk would require another select, which is not great.