0

I have a table_A -

id  |   name  |  is_active |
----+---------+------------+
1   |  jon    |    1       |
2   |  ham    |    0       |
3   |  gary   |   null     |

I have a table_B -

id  |   name  |
----+---------+
1   |  jon    |
2   |  ham    |

I want to remove rows from table B that have is_active value as 0 OR null in table A. So I'm thinking about an INNER JOIN on id column and applying a WHERE clause.

DELETE ROWS from table_B B
INNER JOIN table_A A ON B.id = A.id
WHERE A.is_active = 0 OR A.is_active IS NULL

I don't want any additional columns or changes in table B after the above query. Is this the right way to do it?

2 Answers 2

2

Instead of JOIN, use exists:

DELETE FROM table_B
    WHERE EXISTS (SELECT 1
                  FROM table_A A
                  WHERE A.id = table_B.id AND
                        (A.is_active = 0 OR A.is_active is null)
                 );
Sign up to request clarification or add additional context in comments.

3 Comments

are you missing a line from your code? because i don't see the exists part
It should immediately follow WHERE (e.g., DELETE ... WHERE EXISTS (SELECT 1 ...)
i'm getting SQL Error [102] [S0001]: Incorrect syntax near ')' on the last line for some reason. Using the exact query as above but with DELETE .. WHERE EXISTS (SELECT 1...);
0

You need to say which table you want to delete from, use the alias if you have one:

DELETE B
FROM table_B B
INNER JOIN table_A A ON B.id = A.id
WHERE (A.is_active = 0 OR A.is_active IS NULL);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.