I have a column name as Item_code which have the values like ‘RAM-1′,’RAM-2’, ‘RAM-2’….’RAM-12’. I have to write procedure in postgreSQL which find maximum value from this column.
CREATE OR REPLACE FUNCTION public.get_last_itemcode(
item text)
RETURNS text
LANGUAGE 'plpgsql'
COST 100
VOLATILE PARALLEL UNSAFE
AS $BODY$
declare
result text;
BEGIN
Select MAX(it.item_code) into result from public.items as it where it.item_name = item;
return result;
END;
$BODY$;
But it gives the value maximum value ‘RAM-9, instead of ‘RAM-15’.
2
Answers
The following should satisfy the stated requirements:
STRICT
has been specified since the function will always return NULL if item is NULL. All of the column and variable references in the query are qualified to protect against name collisions. Type declarations reference the relevant table columns to help protect against incompatible schema changes.To get the max, you will need to descending order records by the extracted number from
item_code
, then take the first one usingLIMIT 1
:Demo here