Answer the question
In order to leave comments, you need to log in
How to add a column to the database with data from another column?
There was a need to add a new item_id column and fill it with id values from another column that looks like
I had an idea to write a function that would return the id value from the jsonb object for the current row and specify this function as the default value, but I don’t know how to pass the value of the item field for the current row.
CREATE FUNCTION public.get_item_id(item items)
RETURNS bigint
LANGUAGE 'sql'
AS $BODY$
SELECT item.item ->> "id"
FROM items
$BODY$;
ALTER FUNCTION public.get_item_id()
OWNER TO postgres;
Answer the question
In order to leave comments, you need to log in
First, add a new column:
ALTER TABLE items ADD COLUMN item_id VARCHAR (16) DEFAULT NULL;
UPDATE items SET item_id = item->>'id';
ALTER TABLE items ADD COLUMN item_id_int BIGINT DEFAULT NULL;
UPDATE items SET item_id_int = (item->>'id')::bigint;
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question