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'
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!
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.
If you omit the WHERE clause from a DELETE statement, SQL removes all the rows from the table.
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.
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)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With