0

I have the following SELECT statement,

SELECT * From MyTable as t
WHERE
t.Key1 =
(SELECT Max(r.Key1) From MyTable as r
WHERE (Key2 = t.Key2 AND Key3 = t.Key3 AND Key4 = t.Key4))
AND
(Key2 = t.Key2 AND Key3 = t.Key3 AND Key4 = t.Key4)

which selects all the records I wish to delete from MyTable. However when I try to actually delete the records i.e. by changing SELECT * to DELETE, I get an error and I believe this is because you cannot use aliases with a DELETE statement.

How then would I go about deleting these selected records from MyTable?

1 Answer 1

1

It is indeed not possible to use an alias for the table name in a DELETE statement.

However, that table still has a name. As long as all other instances of this table have an alias, you can unambiguously refer to any of them:

DELETE From MyTable
WHERE
MyTable.Key1 =
(SELECT Max(r.Key1) From MyTable as r
WHERE (Key2 = MyTable.Key2 AND Key3 = MyTable.Key3 AND Key4 = MyTable.Key4))
AND
(Key2 = MyTable.Key2 AND Key3 = MyTable.Key3 AND Key4 = MyTable.Key4)

(The last line of this query does not make sense, because it is not part of the subquery and Key2 and MyTable.Key2 refer to the same table.)

Sign up to request clarification or add additional context in comments.

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.