create table test (id int primary key, parent_id int);
insert into test values (1, null), (2, null), (3, 1), (4, 1), (5, 2), (6, 2), (7, 12), (8, 21);
-- get records with wrong parents
select *
from test
where
parent_id is not null
and not exists (
select id from test as parents where parents.id = test.parent_id
);
-- delete records with wrong parents
delete test.*
from test
left join test as parents on parents.id = test.parent_id
where test.parent_id is not null and parents.id is null;
select * from test;
-- add foreign key to prevent missing parents
alter table test add foreign key (parent_id) references test(id);