I have this table named ‘Details’ with 4 columns.
name | age | occupation | birth_year |
---|---|---|---|
jav | 25 | null | 1997 |
david | null | null | 2000 |
The requirement is if I insert a value in occupation column, I want this to insert on the first null row. Which means, I want the null rows of the column to be filled first.
For example,
insert into details(occupation)
values('student');
I want to create a function which will return the result like this if I just insert any new value
name | age | occupation | birth_year |
---|---|---|---|
jav | 25 | student | 1997 |
david | null | null | 2000 |
My question is, how to update the values of a column in a single query if the value is null then update with the new value.
I’ve come with these two function.
CREATE OR REPLACE FUNCTION update_null_value(value int)
RETURNS VOID AS $$
BEGIN
UPDATE details
SET occupation = value
WHERE occupation IS NULL
RETURNING occupation
INTO value;
SELECT value
FROM details
WHERE occupation= value
LIMIT 1;
END;
$$ LANGUAGE plpgsql;
Whenver I pass a value, I get this error.
ERROR: query returned more than one row
HINT: Make sure the query returns a single row, or use LIMIT 1.
CONTEXT: PL/pgSQL function update_null_value(integer) line 3 at SQL statement
SQL state: P0003
If I limit 1 in the update, like this function. I get ERROR: syntax error at or near “limit” as we cant use limit 1 in update.
CREATE OR REPLACE FUNCTION update_null_value(value int)
RETURNS VOID AS $$
BEGIN
INSERT INTO organization_map (organization_id)
VALUES (value);
UPDATE organization_map
SET organization_id = value
WHERE organization_id IS NULL
limit 1
RETURNING organization_id
INTO value;
SELECT value
FROM organization_map
WHERE organization_id = value
order by organization_id
LIMIT 1;
END;
$$ LANGUAGE plpgsql;
How to create a function the works for all the columns and rows.
Please help.