Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where not exists in delete

A simple issue I'm having. I'm getting a syntax error from the following SQL:

DELETE FROM Blog.Category c 
WHERE NOT EXISTS (SELECT * FROM Blog.Posts p
                  WHERE p.postCategory = blog.Category.catId)

Obviously I'm missing something silly here. Any hints would be appreciated.

EDIT

I have also tried

DELETE FROM Blog.Category c 
where NOT EXISTS(SELECT * FROM Blog.Posts p WHERE  p.postCategory = c.catId)

However I get

Incorrect syntax near 'c'

like image 380
M_Griffiths Avatar asked Jul 31 '18 15:07

M_Griffiths


People also ask

Can we use WHERE clause in DELETE?

DELETE Syntax Notice the WHERE clause in the DELETE statement. The WHERE clause specifies which record(s) should be deleted. If you omit the WHERE clause, all records in the table will be deleted!

Can DELETE work without WHERE clause?

Example - DELETE Statement with One ConditionIf you run a DELETE statement with no conditions in the WHERE clause, all of the records from the table will be deleted. As a result, you will most often include a WHERE clause with at least one condition in your DELETE statement.

What happens if you omit the WHERE clause in the DELETE statement?

If you omit the WHERE clause from a DELETE statement, SQL removes all the rows from the table.

WHERE not exists in SQL?

NOT EXISTS is used with a subquery in the WHERE clause to check if the result of the subquery returns TRUE or FALSE. The Boolean value is then used to narrow down the rows from the outer select statement.


2 Answers

You are missing the alias directly after the DELETE statement.

DELETE c FROM Blog.Category c 
WHERE NOT EXISTS(SELECT * FROM Blog.Posts p WHERE  p.postCategory = c.catId)

Alternatively you can omit the alias and use the full table name.

DELETE FROM Blog.Category
WHERE NOT EXISTS(SELECT * FROM Blog.Posts p WHERE  p.postCategory = Blog.Category.catId)
like image 92
Igor Avatar answered Nov 15 '22 09:11

Igor


I like updating and deleting alias'd tables better as I feel it is more clear.

DELETE c
FROM Blog.Category c
left join Blog.Posts p ON p.postCategory = c.catId
WHERE p.postCategory IS NULL

The issue in your query is you alias the table and then don't use it in the EXISTS.

like image 41
UnhandledExcepSean Avatar answered Nov 15 '22 10:11

UnhandledExcepSean