By using db<>fiddle, you agree to license everything you submit by Creative Commons CC0.
create table story_category(category_id int);
create table category (id int);
insert into story_category values (1), (2), (3), (4), (5);
insert into category values (4), (5), (6), (7);
Records: 5 Duplicates: 0 Warnings: 0
Records: 4 Duplicates: 0 Warnings: 0
SELECT *
FROM story_category
WHERE category_id NOT IN (
SELECT DISTINCT category.id
FROM category INNER JOIN
story_category ON category_id=category.id);
category_id |
---|
1 |
2 |
3 |
select sc.*
from story_category sc
where not exists (select 1 from category c where c.id = sc.category_id)
category_id |
---|
1 |
2 |
3 |
delete from story_category
where not exists (select 1 from category c where c.id = story_category.category_id);
select * from story_category;
category_id |
---|
4 |
5 |