I have a procedure, where I have to check a certain view for some specified entries and delete them accordingly. I have used the following approach for this purpose –
SELECT id_1,
id_2,
id_3,
id_4
INTO v_id_1,
v_id_2,
v_id_3,
v_id_4
FROM v_doc
WHERE parent_id_1 = p_id_1 -- 'p_' suffix stands for function parameters
AND parent_id_2 = p_id_2
AND parent_id_3 = p_id_3
LIMIT 1
;
WHILE v_id_1 IS NOT NULL
LOOP
-- Code for child document line deletion goes here
SELECT id_1,
id_2,
id_3,
id_4
INTO v_id_1,
v_id_2,
v_id_3,
v_id_4
FROM v_doc
WHERE parent_id_1 = p_id_1
AND parent_id_2 = p_id_2
AND parent_id_3 = p_id_3
LIMIT 1
;
END LOOP;
Is this is the efficient way, or there is a more efficient way to do this type of query? I am talking about the way I am selecting the records, of course.
I think you’re wondering how you can delete each matching item, if your query returns many rows. A quicker and correcter way is to run the query once, and loop over its rows:
See http://www.postgresql.org/docs/8.4/static/plpgsql-control-structures.html#PLPGSQL-RECORDS-ITERATING
An even better way might be to simply use a
DELETE FROM x WHERE ...statement, if possible. It depends how simple the deletion is.